获取与多维数组中的值匹配的元素

获取与多维数组中的值匹配的元素

问题描述:

我有一个多维数组。

我想获取数组中与某个值匹配的元素。

I want to get the element in the array that matches a certain value.

Array:

$userdb=Array
(
    (0) => Array
        (
            (id) => '0',
            (name) => 'Sandra Shush',
            (url) => 'urlof100'
        ),

    (1) => Array
        (
            (id) => '1',
            (name) => 'Stefanie Mcmohn',
            (pic_square) => 'urlof100'
        ),

    (2) => Array
        (
            (id) => '2',
            (name) => 'Michael',
            (pic_square) => 'urlof40489'
        )
);

获取数组元素的代码,其中 id = 2

Code to get array element where id = 2:

$key = array_search(2, array_column($userDB, 'id'));

当前代码未返回任何内容。

Current code is not returning anything.

您可以循环遍历数组,并在找到符合条件的元素时停止。

You can just loop over the array, and when you find the element that meets your criteria, stop.

$id = 2;
$found_user = null;
foreach ($userdb as $user) {
    if ($user['id'] == $id) {
        $found_user = $user;
        break;
    }
}

使用您当前的代码, $ key 应该设置为 2 ,但是请记住,变量名区分大小写,(所以 $ userdb!= $ userDB )。如果您只想获取密钥,则只要您使用正确的变量名,它就应该起作用。如果要获取整个元素,则可以直接使用array_search返回的键:

With your current code, $key should be set to 2, but remember that variable names are case sensitive, (so $userdb != $userDB). If you just want to get the key, it should work as long as you are using the correct variable name. If you want to get the entire element, then you can use the key returned by array_search directly:

$user = $userdb[array_search(2, array_column($userdb, 'id'))];