本文介绍了如何从PHP中的JSON数组中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JSON数组.我想删除编号为 4
的条目,并返回剩余的数组
I have a JSON array. I want to delete the entry that have number 4
and return the left over array
$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
并没有给我我想要的东西.我希望它返回如下内容:
But this echo
does not give me what I want. I want it to return something like this:
{"1":1,"2":2}
推荐答案
您要删除数组的第四个值,而不是该值.改用 array_search
You're removing the fourth value of the array, not the value. Use array_search instead
$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 );
这篇关于如何从PHP中的JSON数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!