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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)