在多维数组中搜索值并在PHP中返回键

时间:2013-08-14 12:45:07

标签: php arrays

我有一个看起来像这样的数组:

$user = array();
$user['albert']['email'] = 'an@example.com';
$user['albert']['someId'] = 'foo1';
$user['berta']['email'] = 'another@example.com';
$user['berta']['someId'] = 'bar2';

现在我想找出哪个用户有某个someId。在此示例中,我想知道谁拥有someId bar2并希望得到结果berta。有没有一个像样的PHP函数或者我必须自己创建它?

2 个答案:

答案 0 :(得分:2)

$id = 'bar2';

$result = array_filter(
  $user,
  function($u) use($id) { return $u['someId'] === $id; }
);

var_dump($result);

注意:这适用于PHP 5.3+ 注2:现在没有理由使用以下任何版本。

答案 1 :(得分:0)

尝试此功能,它将返回匹配数组。

function search_user($id) {
    $result = new array();
    foreach($user as $name => $user) {
       if ($user['someId'] == 'SOME_ID') {
           $result[] = $user;
       }
    }
    return $result;
}

如果你总是有一个具有相同id的用户,那么你可以只返回一个用户,否则抛出异常

function search_user($id) {
    $result = new array();
    foreach($user as $name => $user) {
       if ($user['someId'] == 'SOME_ID') {
           $result[] = $user;
       }
    }
    switch (count($result)) {
        case 0: return null;
        case 1: return $result[0];
        default: throw new Exception("More then one user with the same id");
    }
}
相关问题