doubei2231 2015-04-26 13:28
浏览 178
已采纳

json_encode返回不确定的结果,数组或对象[重复]

This question already has an answer here:

I find a weird result of json_encode today in my production code, sometimes it returns an array, like ["perl","php","python"], but sometimes an object, like {"0":"perl","2":"python"}. Here is a minimal example:

$a = array("perl", "php", "python", "something other");
foreach($a as $index => $item) 
{
    if ($item == "something")
        unset($a[$index]);
}
echo json_encode($a);

Why does this happen?

</div>
  • 写回答

1条回答 默认 最新

  • dsdapobp26141 2015-04-26 13:28
    关注

    In the foreach loop, once $item == "something" is true, the array keys are not consecutively numerically indexed (except last iteration), then json_encode returns an object. If all the values in the array are not equal to "something", it returns an array. Since array is always what I want, I use array_values() before json_encode.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 电脑鼠标键盘不好使了
  • ¥15 求糕手!用matlab求解目标规划模型🙏
  • ¥15 画出的分类图不对,求解答一下
  • ¥20 springboot和springcloud版本问题
  • ¥15 ps2手柄控制树莓派小车
  • ¥30 C#:vsto powerpoint的外接程序
  • ¥30 stata将do文件代码转化为ado文件
  • ¥15 两个同维数组相比,不同位置、出现重复比无意义,而不同位置、不出现重复比,则有意义。把有意义的两个数组放入新的集合MK中。
  • ¥15 可以远程电脑安装nvm
  • ¥15 写一个可直接调用的函数,将32位有符号数转成另一个无符号的数