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.

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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置