我需要找到一个给定两个值的多维数组的索引,其中一个值是多次重复的,因为它是一个州和城市的列表,下面是一个例子。
array(
99773000 => array('State' => 'ANTIOQUIA', 'City' => 'CUMARIBO'),
99624000 => array('State' => 'ANTIOQUIA', 'City' => 'SANTA ROSALIA'),
99524000 => array('State' => 'VICHADA', 'City' => 'LA PRIMAVERA'),
99001000 => array('State' => 'VICHADA', 'City' => 'PUERTO CARREÑO'),
.....
xxxxxxxx => array('State') => etc......
);
现在,我在函数中收到一个州和一个城市,我需要返回索引,这就是我现在的做法。
foreach ( $array as $index => $state_and_city ) {
$current_state = $state_and_city['State'];
$current_city = $state_and_city['City'];
if( $current_state == $state && $current_city == $city) {
return $index;
}
}
return '';
我想知道是否有更有效的方法?
这里你只需要从内部数组中获取键,可以通过以下方法实现 array_search
职能。
foreach ($array as $index => $state_and_city ) {
$current_state = $state_and_city['State'];
$current_city = $state_and_city['City'];
$state_key = array_search($current_state,$index);
$city_key = array_search($current_city,$index);
if($state_key == $state && $city_key == $city) {
return $index;
}
}
return '';