5

I have an array of json objects like so:

[{"a":"b"},{"c":"d"},{"e":"f"}]

What is the best way to turn this into a php array?

json_decode will not handle the array part and returns NULL for this string.

1
  • Works fine for me. If you use json_decode($arr, true) you'll get a Associative Array. Otherwise, you'll get an array of Objects. Perhaps that is the problem you are having? Commented Apr 7, 2010 at 16:38

2 Answers 2

18

json_decode() does so work. The second param turns the result in to an array:

var_dump(json_decode('[{"a":"b"},{"c":"d"},{"e":"f"}]', true));

// gives

array(3) {
  [0]=>
  array(1) {
    ["a"]=>
    string(1) "b"
  }
  [1]=>
  array(1) {
    ["c"]=>
    string(1) "d"
  }
  [2]=>
  array(1) {
    ["e"]=>
    string(1) "f"
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

When the second parameter is true, "returned objects will be converted into associative arrays"
My version (PHP 5.2.9, json 1.2.1) also properly parses the json string into an array.
Yeah my bad. The code to scrape the json from the page was flawed. thanks.
6
$array = '[{"a":"b"},{"c":"d"},{"e":"f"}]';
print_r(json_decode($array, true));

Read the manual - parameters for the json_decode method are clearly defined: http://www.php.net/manual/en/function.json-decode.php

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.