I am trying to use json_decode() as follows:
<?php
//Este es el json
$fol ='[{"name":"Taili Silva","screen_name":"taili_silva","id":837254166619770880,"id_str":"837254166619770880","connections":["following","followed_by"]}]';
$str =json_decode($fol, TRUE);
echo $str['connections'];
?>
and this is the error:
Notice: Array to string conversion in line 3
Could you give me some explanation or solution
Use
var_dump($str);
to print the arrays orprint_r($str);
echo
does not print arraysThe advertisement
it is given in this case because you are trying to print with
echo
an array, which is impossible.If you want to print the array just to check what's inside it, you can use
print_r
,var_dump
orvar_export
.If you need to store it in a variable or print it with
echo
you have to iterate through the array in a loop and retrieve its values.Also, in the data you have, it
connections
is itself an array:Therefore, it is impossible to access its values directly as you are doing. If you don't want to use loops anyway, you can access each value in this inelegant and impractical way, especially on arrays with many values:
Print:
Y
Print:
Let's see:
Result:
In addition, your JSON has another supplementary situation, and that is that, being between
[]
, it is a JSON array, which is not the same as a JSON object, since the latter are enclosed in{}
.If you want to directly access an array property then you have to put the index in front of it.
For example:
Will result in:
If it were a JSON object (without
[]
):So you could read it like this:
Result:
PS: If you are interested, later I will complete a demo with more details.