开发者

Find array keys

In PHP I have an array that looks like this:

$array[0]['width'] = '100';
$array[0]['height'] = '200';
$array[2]['width'] = '150';
$array[2]['height'] = '250';
  • I don't know how many items there are in the array.
  • Some items can be deleted which explains the missing [1] key.

I want to add a new item after this, like this:

$array[]['width'] = '300';
$array[]['height'] = '500';

However the code above don't work, because it adds a new key for each row. It should be the same for the two rows above. A clever 开发者_运维技巧way to solve it?

An alternative solution would be to find the last key. I failed trying the 'end' function.


The correct way to do this is:

$array[] = array(
  'width' => 200,
  'height' => 500,
);

because you're actually adding a new array to $array.


How about

$array[] = array("width" => "300", "height" => "500");


Or, just for completeness and obviousness, use a temporary array:

$t=array();
$t['width']='300';
$t['height']='500';

And then add it to the main array:

$array[]=$t;


Another solution, useful when you cannot add both values in a single statement:

$a = array();
$array[] &= $a; // Append a reference to the array, instead of a copy

$a['width'] = '300';
$a['height'] = '500';

But you can also retrieve the last key in the array:

$array[]['width'] = '300';

end($array); // Make sure the internal array pointer is at the last item
$key = key($array);  // Get the key of the last item

$array[$key]['height'] = 300;


If you don't mind it losing those keys, you could easily fix the problem by re-indexing.

$array = array_values($array);
$i = count($array);
$array[$i]['width'] = '300';
$array[$i]['height'] = '500';

However, if you don't want to do this, you could also use this:

$array[] = array(
    'width' => '300',
    'height' => '500'
);

Which will create a new array and inserts it as a second dimension.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜