2

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?

1
  • You are encouraged to use jq that is best suited for such jobs. You might want to check my [ other answer ] on a similar question. Commented Sep 5, 2016 at 10:12

3 Answers 3

2

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"];
}
Sign up to request clarification or add additional context in comments.

Comments

0

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');

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.