0
$arr = array (

    0 => array(
        'id' => 1,
        'name' => 'john'
    ),
    1 => array(
        'id' => 4,
        'name' => 'elisabeth'
    )
);

假设我们只知道内部数组的“id”,那么搜索包含我们 id 的数组的 $arr 元素的最佳方法是什么?

4

4 回答 4

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...
        }
    }
}
于 2013-03-19T16:05:45.190 回答
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"];
于 2013-03-19T16:05:33.483 回答
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>';
于 2013-03-19T16:07:51.420 回答
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);
于 2013-03-19T16:29:46.777 回答