小编tod*_*sby的帖子

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.
 }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

更新方案

 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); …
Run Code Online (Sandbox Code Playgroud)

php arrays object array-splice

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

array-splice ×1

arrays ×1

object ×1

php ×1