Search for data in a JSON

-1

I would like to know how to search data within a JSON through PHP. I have a JSON code that contains a huge list of cities with their id codes and I want the user to ask a city and the program written in PHP look for the city within the json, see similar cities, return those matches to the user, this one choose and once we know the exact city, we look for it in the json and let's get the code from it.

So, how do I do that PHP search of the city in a JSON? The JSON has these characteristics:

[
 {
  "id": 707860,
  "name": "Hurzuf",
  "country": "UA",
  "coord": {
     "lon": 34.283333,
     "lat": 44.549999
  }
 },
 {
  "id": 519188,
  "name": "Novinki",
  "country": "RU",
  "coord": {
     "lon": 37.666668,
     "lat": 55.683334
  }
 }
]

Thank you very much for the help.

    
asked by Evelyn García 24.07.2018 в 17:59
source

1 answer

1

Assuming that you already have the JSON in an associative array, you could run it with a foreach and then save the results you want in another associative array. Then you can manipulate the results as you wish. Something like this:

$resultados = array();
$buscar = $_POST['buscar'];
foreach($ciudades as $i => $ciudad) {
    if(strpos($ciudad['name'], $buscar) != FALSE) {
        $resultados[$ciudad['id']] = $ciudad['name'];
    }
}
    
answered by 24.07.2018 / 18:07
source