I.Swen I.Swen - 21 days ago 7
PHP Question

Find the value in a multidimensional array by key

UPD code: "Parse error: syntax error, unexpected '[' in E"

I need to find the array element value on the key value, which is obtained from a variable. In my code somewhere error. Can you help me please? Thanks!

$city_file = 'https://pogoda.yandex.ru/static/cities.xml';
$xml_city = simplexml_load_file($city_file);
$cityName = 'Киев';

foreach($xml_city->country as $country){
foreach($country->city as $city):
$attrs = $city->attributes();
$city = strval($city);
$id = strval($attrs['id']);
$cities = [];
$cities [] = [$id=>$city];
endforeach;
}
$cityid = array_search($cityName, $cities);
echo $cities;
echo $cityid;


UPD 2: Thanks for all, this version is works

$city_file = 'https://pogoda.yandex.ru/static/cities.xml';
$xml_city = simplexml_load_file($city_file);
$cityName = 'Осака';
//$cities = []; - Syntax error
foreach($xml_city->country as $country){
foreach($country->city as $city):
$attrs = $city->attributes();
$city = strval($city);
$id = strval($attrs['id']);
$cities [$id] = $city;
endforeach;
}

$cityid = array_search($cityName, $cities);
echo $cityid;

Answer

Define

   $cities = [];

And below fix this:

  $cities [] = [$id=>$city];

Updated:

  $city_file = 'https://pogoda.yandex.ru/static/cities.xml';   
  $xml_city = simplexml_load_file($city_file); 
  $cityName = 'Киев';
  $cities = [];
 foreach($xml_city->country as $country){
  foreach($country->city as $city):
   $attrs = $city->attributes();
   $city = strval($city);
   $id = strval($attrs['id']);

   $cities [] = [$id=>$city];
  endforeach;
}
$cityid = array_search($cityName, $cities);
print_r($cities);

Update 2:

OK I manually ran the code and still there was an error. And now here is the complete code:

  $city_file = 'https://pogoda.yandex.ru/static/cities.xml';   
  $xml_city = simplexml_load_file($city_file); 
  $cityName = 'Киев';
  $cities = [];
  foreach($xml_city->country as $country){
    foreach($country->city as $city):
      $attrs = $city->attributes();
      $city = strval($city);
      $id = strval($attrs['id']);

      $cities [$id] = $city;
    endforeach;
  }
  $cityid = array_search($cityName, $cities);
  print_r($cities[$cityid]);

Hope it helps.