简体   繁体   中英

Delete one item from array with matching keys

I have an array

$array = ['f'=>'foo', 'f'=>'foo', 'f'=>'foo','g'=>'good'];

and I want to delete only one item from this array with matching key, like the following:

unset($array['f']);

However, this will delete the all items with this matching key 'f' and only one item will remain. Is there a way to do something like this, but apply it only to the first matching item in the array?

First of all you have a syntax error.

$array=$array(['f'=>'foo', 'f'=>'foo', 'f'=>'foo','g'=>'good']);

You have an $ extra and [] extras, and you can't have a lots off records with the same key(because the last one will override the previously)... The correct way to define

$array= array('f'=> array('foo', 'foo2', 'foo3'), 'g'=>'good');

The values will be a new array inside de F key. And then you can remove only one record

unset($array['f'][0]);

now your arrays var_dump:

$array= array('f'=> array('foo2', 'foo3'), 'g'=>'good');

我已经根据cmorrissy评论使用它解决了这个问题,只有一个项目,所以该变量向我显示了数量,我必须检查是否

if($product[$id]['quantity']>1){ $product[$id]['quantity']--;}else{unset($product[$id]);}

if you var_dump($array); this would be the output

var_dump($array);
array(
    f => foo
    g => good
 )

since you have an array with the same index it will be displayed as one, and thats why it will be deleted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM