php从对象数组中删除对象

php从对象数组中删除对象,php,arrays,object,array-splice,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('l

我试图通过对象的“索引”从对象数组中删除对象。这是我到目前为止得到的,但我被难住了

$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.
 }
}
任何帮助都将不胜感激

更新的解决方案
您必须在阵列上使用函数
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);
?>

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

unset($objectarray[$index]);

你到底想删除什么?
2=>array('label'=>'foobar','value'=>'n2314'
@toddsby那一定是别的东西了…我刚刚测试了这个,它工作得很好。你是在之后还是之前进行了任何未设置?你是对的,我在这段代码之前有一个格式错误的if语句,它导致了
$objectarray='';
。你的解决方案工作正常,但我认为
array\u splice将对我的用例更有效。我更新了我的问题。“你的数组将有奇数索引…”。你解决了我的问题。Thx
$foo2 = array_values($objectarray);
unset($objectarray[$index]);
    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