2

How can I parse json array string to array on php

'[{"a": "1", "b": "2"}, {"a": "3"}]'

seems json_decode allows parse only objects but not arrays. Should it be manually parsed to array before using json_decode?


Seems problem in string. I get a variable with json, and if I output it, looks like the json is valid

echo($jsonvar); //result [{"title":"Home","id":"/","url":"/"}]

but when I try parse string from the variable, the result is nothing even when string is trimmed

echo('[{"title":"Home","id":"/","url":"/"}]', true); //nice parsed array
echo($jsonvar, true); //nothing
echo(trim($jsonvar, " \t\n\r\0\x0B"), true); //nothing
3
  • 2
    How has this gotten two votes? If the documentation was actually read then this question would of never gotten asked. From the doc: When TRUE, returned objects will be converted into associative arrays. ` Commented Mar 13, 2014 at 9:00
  • Believe or not, json_decode() can actually decode JSON; any kind of valid JSON. I can't figure out how you reached a different conclusion. Commented Mar 13, 2014 at 9:03
  • The problem has been solved with the following code json_decode(html_entity_decode($jsonvar));, Sorry for the dumb question, it cannot be removed because of answers. I thought the reason was in array. Commented Mar 13, 2014 at 10:47

2 Answers 2

7

Pass the true as a second parameter to your json_decode() to parse the json string to array.

$json='[{"a": "1", "b": "2"}, {"a": "3"}]';
$arr= json_decode($json,true); 
print_r($arr);
Sign up to request clarification or add additional context in comments.

Comments

0

You can get the json into array by using the true flag in json_decode()

<?php
$str = '[{"a": "1", "b": "2"}, {"a": "3"}]';
$arr=json_decode($str,true);
print_r($arr);

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.