如何从PHP中的JSON数组中删除对象

时间:2016-10-17 14:42:05

标签: php arrays json

我有一个JSON数组。我想删除编号为4的条目,并将左侧数组返回

$filters = '{"1":1,"2":2,"3":4}';
$fobj = json_decode($filters, TRUE);

foreach($fobj as $key => $value) 
{ 
if (in_array(4, $fobj)) {
 unset($fobj[4]);
  }
}
echo $filters = json_encode($fobj );

但这echo并没有给我我想要的东西。我希望它返回这样的东西:

  {"1":1,"2":2}

2 个答案:

答案 0 :(得分:4)

您正在删除数组的第四个值,而不是值。请改用array_search

$filters = '{"1":1,"2":2,"3":4}';
$fobj = json_decode($filters, TRUE);
$search = array_search(4, $fobj);
if($search !== false) unset($fobj[$search]);
echo $filters = json_encode($fobj );

答案 1 :(得分:0)

$index = array_search("4", $array);
unset($array[$index]);

http://php.net/manual/de/function.array-search.php

http://php.net/manual/de/function.unset.php

这就是全部。希望它有所帮助!