Parse JSON string contents into PHP Array

前端 未结 4 1778
孤街浪徒
孤街浪徒 2020-11-29 10:31

I am trying to parse a string in JSON, but not sure how to go about this. This is an example of the string I am trying to parse into a PHP array.

$json = \'{         


        
相关标签:
4条回答
  • 2020-11-29 11:02

    Try 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"
    
    0 讨论(0)
  • 2020-11-29 11:13

    It can be done with json_decode(), be sure to set the second argument to true because you want an array rather than an object.

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

    Outputs:

    Array
    (
        [id] => 1
        [name] => foo
        [email] => foo@test.com
    )
    
    0 讨论(0)
  • 2020-11-29 11:13
    $obj=json_decode($json);  
    echo $obj->id; //prints 1  
    echo $obj->name; //prints foo
    

    To put this an array just do something like this

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

    Now you can use this like

    $arr[0] // prints 1
    
    0 讨论(0)
  • 2020-11-29 11:19

    You can use 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"
        }
    

    How to use: $object->id //1

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

    How to use: $array['id'] //1

    0 讨论(0)
提交回复
热议问题