php从对象数组中删除对象

时间:2014-02-04 17:51:33

标签: php arrays object array-splice

我正在尝试通过'索引从对象数组中删除对象。这是我到目前为止所得到的,但我很难过。

$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 

3 个答案:

答案 0 :(得分:8)

    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

答案 1 :(得分: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);

答案 2 :(得分:2)

在这种情况下,您不需要直接取消直播

unset($objectarray[$index]);