dongshou9878 2012-04-26 21:41
浏览 23
已采纳

PHP JSON解码

I am trying to change a PHP script so that it can recieve a JSON object and work with that given JSON object. Everything works fine until I try to cycle trhough the converted-from-JSON-array-of-objects (aka 'stuff') with the for loop.

What am I doing wrong here:

$json = '{

    "foo":  "hi",
    "bar":  "bye"
    "stuff": [{"widget":"dd"},{"thing":"cc"},{"wcha":"dd"}] 
}';

$arr = json_decode($json, true);
$foo = $arr['foo']; //works fine
$bar = $arr['bar']; //works fine

//old way that worked:
//$stuff    = array("widget" => "dd", "thing" => "cc", "wcha" => "dd");
//new way that does not work:
$stuff = $arr['stuff'];
...

//This is where the problem is:
foreach ($stuff as $key => $value){...

The problem in the for loop is that $key is an integer (not the actual value) and $value is the word 'Array' (not the actual value).

  • 写回答

3条回答 默认 最新

  • duan0802 2012-04-26 21:46
    关注

    It's doing exactly what it should. The problem is that you're not quite understanding it right.

    "stuff" is an array of objects. So when you decode it, the resulting PHP array is this:

    [stuff]=>
    array(3)
      {
      [0]=>
      array(1)
        {
        [widget]=>string(2) "dd"
        }
      [1]=>
      array(1)
        {
        [thing]=>string(2) "cc"
        }
      [2]=>
      array(1)
        {
        [wcha]=>string(2) "dd"
        }
      }
    

    So when you call foreach on it, you're getting the individual arrays from there.

    I think your JSON should be:

    "stuff": {"widget":"dd","thing":"cc","wcha":"dd"}
    

    Either that, or your PHP code should be:

    foreach($stuff as $element) {
        list($key,$value) = each($element);
        // now do stuff
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计