Josh Murray Josh Murray - 1 year ago 52
JSON Question

json, php - output string from array

I am trying to decode JSON data to PHP then output it to the site. If I have the following:

"name": "josh",
"type": "human"

I can do this (within PHP), to display or output my

$file = "path";
$json = json_decode($file);

echo $json["type"]; //human

So, if I have the following:

"name": "josh",
"type": "human",
"friends": [
"name": "ben",
"type": "robot"
"name": "tom",
"type": "alien"
"img": "img/path"

How can I output what
my friend

Answer Source

Use a loop like foreach and do something like the following:

//specify the name of the friend like this:
$name = "ben";

$friends = $json["friends"];

//loop through the array of friends;
foreach($friends as $friend) {
    if ($friend["name"] == $name) echo $friend["type"];