Josh Murray
Josh Murray

Reputation: 637

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?

Upvotes: 2

Views: 81

Answers (3)

Dave
Dave

Reputation: 3091

try this,

$friend_name = "ben";
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $val){
    if($friend_name == $val->name)
    {
        echo "name = ".$val->name;
        echo "type = ".$val->type;
    }    
}

DEMO

Upvotes: 0

Professor Abronsius
Professor Abronsius

Reputation: 33823

To get the decoded data in array format you would supply true as the second argument to json_decode otherwise it will use the default which is object notation. You could easily create a function to shorten the process when you need to find a specific user

$data='{
  "name": "josh",
  "type": "human",
  "friends": [
    {
      "name": "ben",
      "type": "robot"
    },
    {
      "name": "tom",
      "type": "alien"
    }
  ],
  "img": "img/path"
}';

$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $friend ){
    if( $friend->name=='ben' )echo $friend->type;
}

function finduser($obj,$name){
    foreach( $obj as $friend ){
        if( $friend->name==$name )return $friend->type;
    }
}

echo 'Tom is a '.finduser($friends,'tom');

Upvotes: 0

rbr94
rbr94

Reputation: 2287

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

Upvotes: 2

Related Questions