按键在多维数组中查找值

时间:2016-11-16 09:42:45

标签: php arrays

UPD代码:“解析错误:语法错误,意外'['在E”

我需要在键值上找到数组元素值,该值是从变量中获取的。在我的代码中某处出错。你能帮我吗?谢谢!

$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:谢谢大家,这个版本是有效的

    $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;

1 个答案:

答案 0 :(得分:2)

定义

   $cities = [];

以下解决此问题:

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

更新:

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

更新2:

好的我手动运行代码但仍然出现错误。现在这里是完整的代码:

  $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]);

希望它有所帮助。