Josh Murray Josh Murray - 3 months ago 8
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
type
:

$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
type
my friend
ben
is?

Answer

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"];
}
Comments