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 
4

3 回答 3

12
    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
于 2014-02-04T21:51:28.393 回答
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);
于 2014-02-04T17:58:10.883 回答
2

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

unset($objectarray[$index]);
于 2014-02-04T18:00:23.677 回答