根据PHP中的键值显示数组中的值

时间:2019-02-24 02:19:00

标签: php arrays

我有这个数组:

Array
(
    [Europa] => Array
        (
            [0] => Array
                (
                    [AVA_Id] => 1
                    [AVA_Country] => France
                    [AVA_City] => Paris
                )
        )
    [America] => Array
        (
            [0] => Array
                (
                    [AVA_Id] => 2
                    [AVA_Country] => Canada
                    [AVA_City] => Ottawa
                )
        )
)

如果国家是City,我想阅读'Europa'部分并获得France

您知道为什么此代码不起作用吗?

foreach($bigArray as $key => $array) {
    $value = $array[2];
    if($bigArray[AVA_Country] == 'France')) {
        echo $bigArray['AVA_City']
    }
    else {
        echo 'No city found';        
    }
}

谢谢。

2 个答案:

答案 0 :(得分:1)

您应该在循环中检查$array,而不是$bigArray。请注意,您在'附近还缺少AVA_Country,并且)语句中还有一个额外的if,而;中缺少了echo $value['AVA_City'] 。另外,您需要使用另一级嵌套来访问AVA*值,并且示例数据中没有$array[2]值,因此我删除了该行代码。

$found = false;
foreach($bigArray as $key => $array) {
    foreach ($array as $value) {
        if($value['AVA_Country'] == 'France') {
            echo $value['AVA_City'];
            $found = true;
        }
    }
    if (!$found) echo "No city found";
}

输出:

Paris

Demo on 3v4l.org

答案 1 :(得分:0)

您不会遍历数组的所有深层内容。

$country = 'France';
$city = '';
$found = false;

foreach($world as $key => $continent) {
  foreach($continent as $k => $region) {
    if($region['AVA_Country'] == $country)) {
      $city = $region['AVA_City'];
      $found = true;
      break;
    }
  }
  if($found) break;
}
echo $city;