douchuang8359 2014-05-12 12:54
浏览 39
已采纳

Php数组 - 无法从数组中获取值[关闭]

$data = '{"name":"CocaCola","price":1,"sync":0,"id":10792}';
$data = json_decode($data);

print_r((array)$data);
//Array ( [name] => CocaCola [price] => 1 [sync] => 0 [id] => 10792 )

print_r((array)$data["id"]);
//nothing?

This piece of code is not logic for me. Can I get any explanation of this behaviour and how to fix it?

  • 写回答

4条回答 默认 最新

  • duanqin9631 2014-05-12 12:57
    关注
    (array)$data["id"]
    

    This is executed as

    (array)($data["id"])
    

    I.e. the result of $data['id'] is cast to an array; not $data cast to an array and then its id index accessed.

    If you want an array, use json_decode(..., true). Otherwise work with objects as objects instead of casting them to arrays all the time over and over.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?