查找数组的键 [英] Find array keys
问题描述
在PHP我有一个数组,看起来像这样:
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';
- 我不知道有多少项目有数组中
- 某些项目可以删除这也解释了失踪[1]键。
我想在此之后添加一个新的项目,如:
I want to add a new item after this, like this:
$array[]['width'] = '300';
$array[]['height'] = '500';
然而,code以上不工作,因为它增加了对每行一个新的密钥。它应该是上面两行相同的。一个聪明的办法来解决呢?
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.
推荐答案
如果你不介意它失去这些键,你可以很容易地重新索引解决这个问题。
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.
这篇关于查找数组的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!