$arr = array (
0 => array(
'id' => 1,
'name' => 'john'
),
1 => array(
'id' => 4,
'name' => 'elisabeth'
)
);
假设我们只知道内部数组的“id”,那么搜索包含我们 id 的数组的 $arr 元素的最佳方法是什么?
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...
}
}
}
$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"];
使用 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>';
$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);