假设我有一个如下所示的数组:
Array
(
[0] => Array
(
[town_id] => 1
[town_name] => ABC
[town_province_id] => 7
)
[1] => Array
(
[town_id] => 2
[town_name] => DEF
[town_province_id] => 4
)
[2] => Array
(
[town_id] => 3
[town_name] => GHI
[town_province_id] => 2
)
)
我想提供价值" DEF"在上面的数组和返回值" 2"。
请帮帮我。
答案 0 :(得分:1)
您可以使用in_array
来获得结果。
$input = 'DEF';
foreach($array as $key=>$value){
if(in_array($input,$value)){
$town_id = $value['town_id'];
}
}
print_r($town_id);
答案 1 :(得分:0)
$key = array_search('DEF', array_column($array, 'town_name'));
示例:
$data = array( array('town_id' => 1, 'town_name' => 'ABC'), array('town_id' => 2, 'town_name' => 'DEF') );
print_r($data);
$key = array_search('DEF', array_column($data, 'town_name'));
print_r($data[$key]['town_id']); // it will have 2
答案 2 :(得分:0)
使用array_search
和array_column
$key = array_search('DEF', array_column($your_arr, 'town_name'));
$your_arr[$key]['town_id']; // should return DEF
注意:array_column
适用于PHP 5> = 5.5.0