0

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

$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 函数,或者我必须自己创建它?

4

2 回答 2

2
$id = 'bar2';

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

var_dump($result);

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

于 2013-08-14T12:47:37.780 回答
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");
    }
}
于 2013-08-14T12:50:01.870 回答