【问题标题】:php remove object from array of objectsphp从对象数组中删除对象
【发布时间】:2024-04-24 11:25:02
【问题描述】:

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

$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 

【问题讨论】:

  • 你到底想删除什么?
  • 2=>array('label'=>'foobar', 'value'=>'n2314'

标签: php arrays object array-splice


【解决方案1】:
    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);
    

    【讨论】:

    • "你的数组会有奇数索引..."。你解决了我的问题。谢谢
    【解决方案3】:

    在这种情况下,您不需要直接取消设置 foreach

    unset($objectarray[$index]);
    

    【讨论】:

    • @toddsby 那么它一定是别的东西......我刚刚测试过它并且它工作得很好。您是在之后还是之前进行任何取消设置?
    • 你是对的,我在这段代码之前有一个格式错误的 if 语句导致$objectarray = '';。您的解决方案有效,但我认为 array_splice 对于我的用例来说会更有效。我已经更新了我的问题。