我得到了下面的数组,我想通过ID检索名称:
Array
(
[0] => Array
(
[id] => 1
[name] => john
)
[1] => Array
(
[id] => 2
[name] => mark
)
etc...
通过双重foreach循环和条件测试是可行的,但是还有更优雅的方法吗?
答案 0 :(得分:2)
假设id
是唯一的...
$arr = [
['id'=1, 'name'='john'],
['id'=2, 'name'='mark'],
];
$lookup = [];
foreach($arr as $row) {
$id = $row['id'];
$name = $row['name'];
$lookup[$id] = $name;
}
// find name for id, 2
echo $lookup[2];
// ==> mark
...请参阅Progrock的解决方案!
答案 1 :(得分:1)
您可以使用array_column将ID映射到名称:
<?php
$arr = [
['id' => 1, 'name' => 'Rolf'],
['id' => 3, 'name' => 'Gary'],
['id' => 2, 'name' => 'Jimmy'],
];
$id_names = array_column($arr, 'name', 'id');
var_export($id_names);
print $id_names[3];
输出:
array (
1 => 'Rolf',
3 => 'Gary',
2 => 'Jimmy',
)Gary