我有这个数组:
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
,我想阅读'欧罗巴'部分并获得France
。
你知道为什么这段代码不起作用吗?
foreach($bigArray as $key => $array) {
$value = $array[2];
if($bigArray[AVA_Country] == 'France')) {
echo $bigArray['AVA_City']
}
else {
echo 'No city found';
}
}
谢谢。
你应该在你的循环中检查$array
,而不是$bigArray
。请注意,你也缺少'
周围的AVA_Country
s,你的)
声明中有一个额外的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
您不会遍历所有深层数组。
$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;