在一个值中搜索mutlidimensional数组并在PHP中返回键

时间:2021-01-13 21:35:30

I have an array looking like this:

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

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

Now I want to find out which user has a certain someId. In this example I want to know who has the someId bar2 and want the result berta. Is there a decent php function for this or would I have to create this on my own?

现在我想找出哪个用户有某个someId。在这个例子中,我想知道谁有someId bar2并想要结果berta。有没有一个像样的PHP功能,或者我必须自己创建它?

2 个解决方案

#1


2  

$id = 'bar2';

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

var_dump($result);

Note: this works in PHP 5.3+.
Note 2: there is no reason to use any version below nowadays.

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

#2


0  

Try this function it will return array of the matches.

尝试此函数它将返回匹配数组。

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

if you always have one user with same id then you can just return one user, and throw exception otherwise

如果你总是有一个具有相同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");
    }
}

#1


2  

$id = 'bar2';

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

var_dump($result);

Note: this works in PHP 5.3+.
Note 2: there is no reason to use any version below nowadays.

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

#2


0  

Try this function it will return array of the matches.

尝试此函数它将返回匹配数组。

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

if you always have one user with same id then you can just return one user, and throw exception otherwise

如果你总是有一个具有相同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");
    }
}