10

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 = '{"id":1,"name":"foo","email":"[email protected]"}';  

Is there some library that can take the id, name, and email and put it into an array?

4 Answers 4

21

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] => [email protected]
)
Sign up to request clarification or add additional context in comments.

Comments

6

Try json_decode:

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

Comments

4
$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

1 Comment

Why not use the second parameter of json_decode? Now you lose the array keys, which seem to be quite usefull here.
1

You can use json_decode()

$json = '{"id":1,"name":"foo","email":"[email protected]"}';  

$object = json_decode($json);

Output: 
    {#775 ▼
      +"id": 1
      +"name": "foo"
      +"email": "[email protected]"
    }

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

$array = json_decode($json, true /*[bool $assoc = false]*/);

Output:
    array:3 [▼
      "id" => 1
      "name" => "foo"
      "email" => "[email protected]"
    ]

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.