简体   繁体   English

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

[英]Get element that matches value in multi-dimensional array

I have a multi-dimensional array. 我有一个多维数组。

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'
        )
);

Code to get array element where id = 2 : 获取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;
    }
}

With your current code, $key should be set to 2 , but remember that variable names are case sensitive, (so $userdb != $userDB ). 在您当前的代码中, $key应该设置为2 ,但是请记住,变量名称区分大小写(因此$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: 如果要获取整个元素,则可以直接使用array_search返回的键:

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

 <?php $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' ) ); //echo $userdb[0]['id']; //-result index id 0 => 0-// //echo $userdb[1]['id']; //-result index id 1 => 1-// //echo $userdb[2]['id']; //-result index id 2 => 2-// $id = 2; foreach($userdb as $value) { if($value['id'] == $id) { var_dump($value); break; } } ?> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM