gpt4 book ai didi

php 从对象数组中删除对象

转载 作者:可可西里 更新时间:2023-11-01 00:00:22 25 4
gpt4 key购买 nike

我正在尝试通过其索引从对象数组中删除一个对象。到目前为止,这是我得到的结果,但我很困惑。

$index = 2;

$objectarray = array(
0=>array('label'=>'foo', 'value'=>'n23'),
1=>array('label'=>'bar', 'value'=>'2n13'),
2=>array('label'=>'foobar', 'value'=>'n2314'),
3=>array('label'=>'barfoo', 'value'=>'03n23')
);

//I've tried the following but it removes the entire array.
foreach ($objectarray as $key => $object) {
if ($key == $index) {
array_splice($object, $key, 1);
//unset($object[$key]); also removes entire array.
}
}

如有任何帮助,我们将不胜感激。

更新的解决方案

 array_splice($objectarray, $index, 1); //array_splice accepts 3 parameters 
//(array, start, length) removes the given array and then normalizes the index
//OR
unset($objectarray[$index]); //removes the array at given index
$reindex = array_values($objectarray); //normalize index
$objectarray = $reindex; //update variable

最佳答案

    array_splice($objectarray, $index, 1); 
//array_splice accepts 3 parameters (array, start, length) and removes the given
//array and then normalizes the index
//OR
unset($objectarray[$index]); //removes the array at given index
$reindex = array_values($objectarray); //normalize index
$objectarray = $reindex; //update variable

关于php 从对象数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21559760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com