加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php从对象数组中删除对象

发布时间:2020-12-13 22:06:13 所属栏目: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'=
我试图通过’索引从对象数组中删除对象.这是我到目前为止所得到的,但我很难过.

$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

解决方法

array_splice($objectarray,1); 
    //array_splice accepts 3 parameters (array,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读