PHP从对象数组中删除对象

5

我试图通过它的索引从对象数组中删除一个对象。这是我目前所拥有的,但我被卡住了。

$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 

你想要移除什么? - FabioG
2=>array('label'=>'foobar', 'value'=>'n2314' - toddsby
3个回答

13
    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

2
你需要在数组上使用unset函数。
因此,代码如下:
<?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')
);
var_dump($objectarray);
foreach ($objectarray as $key => $object) {
    if ($key == $index) {
        unset($objectarray[$index]);
    }
}

var_dump($objectarray);
?>

请记住,执行此操作后,您的数组将具有奇数索引,并且如果需要,您必须重新索引它。

$foo2 = array_values($objectarray);

你的数组将会有奇数索引...。你解决了我的问题。谢谢。 - Coisox

2
在这种情况下,您不需要使用foreach,直接取消设置即可。
unset($objectarray[$index]);

@toddsby,那一定是其他问题了...我刚测试过,它完美地运行了。你之后或之前有进行任何未设置的操作吗? - FabioG
你是正确的,我在这段代码之前有一个格式不正确的if语句,导致$objectarray ='';。你的解决方案可行,但我认为对于我的用例来说,使用array_splice会更加高效。我已经更新了我的问题。 - toddsby

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接