如何在php子数组中搜索?
我在php中有以下数组:如何在php子数组中搜索?,php,mysql,arrays,loops,Php,Mysql,Arrays,Loops,我在php中有以下数组: Array ( [0] => Array ( [city] => London [institute_count_per_city] => 10 ) [1] => Array ( [city] => Leeds [institute_count_per_city] => 10 ) [2] => Array
Array
(
[0] => Array
(
[city] => London
[institute_count_per_city] => 10
)
[1] => Array
(
[city] => Leeds
[institute_count_per_city] => 10
)
[2] => Array
(
[city] => Edinburgh
[institute_count_per_city] => 10
)
[3] => Array
(
[city] => GrandTotal
[institute_count_per_city] => 30
)
)
现在,最后一个子数组将始终具有常量key=>value([city]=>GrandTotal)。我想得到[city]=>GrandTotal的[institute\u count\u per\u city]值
实现这一点的有效方法是什么。没有比迭代所有元素并检查值是否匹配更好的方法了
$result = null;
foreach($arr as $key => $item) {
if($item['city'] == 'GrandTotal') {
$result = $item;
break;
}
}
既然你说这永远是最后一次。。。简单快捷:
$GrandTotal = $array[count($array) -1]['institute_count_per_city'];
这将始终是主阵列中的最后一个子阵列。没有任何函数可以直接返回最后一个子数组吗?我的意思是我将得到主数组的大小,然后得到最后一个索引上的子数组。@RishabGarg在这里看到Silvertiger的答案。谢谢。这太完美了!!!