编程语言
首页 > 编程语言> > php从对象数组中删除对象

php从对象数组中删除对象

作者:互联网

我试图通过’索引从对象数组中删除对象.这是我到目前为止所得到的,但我很难过.

$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,object,arrays,array-splice
来源: https://codeday.me/bug/20190715/1467481.html