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?

asked Sep 5, 2016 at 9:49
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"];
}
answered Sep 5, 2016 at 9:53
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');
answered Sep 5, 2016 at 9:53

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

answered Sep 5, 2016 at 10:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.