【问题标题】:Parse JSON string contents into PHP Array将 JSON 字符串内容解析为 PHP 数组
【发布时间】:2012-11-28 07:33:48
【问题描述】:

我正在尝试解析 JSON 格式的字符串,但不知道该怎么做。这是我试图解析为 PHP 数组的字符串示例。

$json = '{"id":1,"name":"foo","email":"foo@test.com"}';  

是否有一些库可以将 id、name 和 email 放入数组中?

【问题讨论】:

    标签: php json


    【解决方案1】:

    您可以使用json_decode()

    $json = '{"id":1,"name":"foo","email":"foo@test.com"}';  
    
    $object = json_decode($json);
    
    Output: 
        {#775 ▼
          +"id": 1
          +"name": "foo"
          +"email": "foo@test.com"
        }
    

    如何使用: $object->id //1

    $array = json_decode($json, true /*[bool $assoc = false]*/);
    
    Output:
        array:3 [▼
          "id" => 1
          "name" => "foo"
          "email" => "foo@test.com"
        ]
    

    如何使用: $array['id'] //1

    【讨论】:

      【解决方案2】:

      可以使用json_decode() 完成,请务必将第二个参数设置为true,因为您需要的是数组而不是对象。

      $array = json_decode($json, true); // decode json
      

      输出:

      Array
      (
          [id] => 1
          [name] => foo
          [email] => foo@test.com
      )
      

      【讨论】:

        【解决方案3】:

        试试json_decode:

        $array = json_decode('{"id":1,"name":"foo","email":"foo@test.com"}', true);
        //$array['id'] == 1
        //$array['name'] == "foo"
        //$array['email'] == "foo@test.com"
        

        【讨论】:

          【解决方案4】:
          $obj=json_decode($json);  
          echo $obj->id; //prints 1  
          echo $obj->name; //prints foo
          

          要将其放入数组中,只需执行以下操作即可

          $arr = array($obj->id, $obj->name, $obj->email);
          

          现在你可以像这样使用它了

          $arr[0] // prints 1
          

          【讨论】:

          • 为什么不用json_decode的第二个参数呢?现在你丢失了数组键,这在这里似乎很有用。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-17
          • 1970-01-01
          • 2012-11-23
          • 1970-01-01
          • 2018-06-11
          相关资源
          最近更新 更多