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 根据会员信息表绘制堆积柱状图
  • ¥100 华为手机私有App后台保活
  • ¥20 有谁能看看我coe文件到底哪儿有问题吗?
  • ¥20 我的这个coe文件到底哪儿出问题了
  • ¥15 matlab使用自定义函数时一直报错输入参数过多
  • ¥15 设计一个温度闭环控制系统
  • ¥100 rtmpose姿态评估
  • ¥15 java 通过反射找路径下的类,打包后就找不到
  • ¥15 通联支付网上收银统一下单接口
  • ¥15 angular有偿编写,