$arr = array (
0 => array(
'id' => 1,
'name' => 'john'
),
1 => array(
'id' => 4,
'name' => 'elisabeth'
)
);
假设我们所知道的只是内部数组的'id',搜索包含数组的$ arr元素的最佳方法是什么?
答案 0 :(得分:1)
function search($id)
{
foreach ($arr as $item) {
if (isset($item['id']) && $item['id'] == $id) {
return $item; // or whatever you want to return
}
}
}
更新:
function search($id)
{
foreach ($arr as $key => $item) {
if (isset($item['id']) && $item['id'] == $id) {
return $key; // Return key...
}
}
}
答案 1 :(得分:0)
$arr = array (
0 => array(
'id' => 1,
'name' => 'john'
),
1 => array(
'id' => 4,
'name' => 'elisabeth'
)
);
foreach($arr as $a)
if($a["id"] == 4)
echo $a["name"];
答案 2 :(得分:0)
使用array_filter
$arr = array (
0 => array(
'id' => 1,
'name' => 'john'
),
1 => array(
'id' => 4,
'name' => 'elisabeth'
)
);
$id = 1;
$result = array_filter($arr, function($el) use ($id) {
return $el['id'] == $id;
});
echo '<pre>', var_dump($result), '</pre>';
答案 3 :(得分:0)
$array = array(
0 => array(
'id' => 1,
'name' => 'john'
),
1 => array(
'id' => 4,
'name' => 'elisabeth'
)
);
$search = 4;
$result = null;
array_walk(
$array,
function ($element) use ($search, &$result) {
if (isset($element['id']) && (int)$element['id'] === (int)$search) {
$result = $element;
}
}
);
var_dump($result);