Get item corresponding to another item from json in php

717

I want to read this JSON using PHP:

{
["person":{
   {"name":"Bill"},  
   {"age":"56"},
   {"city":"Houston"}
}],
["person":{  
   {"name":"Jack"},
   {"age":"45"},
   {"city":"Dallas"}
}],
["person":{
   {"name":"Henry"},
   {"age":"33"},
   {"city":"Atlanta"}
}]
}

Now I want to look for the person who's name is Jack and get the city he lives in. I know how to check for the name. But how can I get the corresponding city then?

17

Answer

Solution:

I think this should make it:

$string = file_get_contents("persons.json");
$json = json_decode($string);

foreach ($json->person as $person) {
   if($person->name == "Jack")
  {
      $city = $person->city;
  }
}

People are also looking for solutions to the problem: php - Laravel 5.3 OAuth2 NotFoundHttpException

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.