简体   繁体   中英

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 :

$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 ). 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'))];

 <?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; } } ?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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