PHP: get a list of values by key from a list of dictionary

Viewed 1694
Array ( 
    [0] => Array (
      [id] => 1 
      [user_id] => 15
      [booked] => 2020-08-01
      [sendin] => 2020-08-03
      [pickup] => 2020-08-08
      [duration] => 5 
    )
    [1] => Array (
      [id] => 2
      [user_id] => 15
      [booked] => 2020-08-01
      [sendin] => 2020-08-03
      [pickup] => 2020-08-08
      [duration] => 5 
    )  
)

to get id, by pass in user_id = 15, I want

$ids = array(1, 2)

Is there a shorthand method for this, or do I have to code a function? Appreciate your help.

2 Answers

You can use array_filter to find all the sub-arrays which have user_id == 15, and then array_map to extract the corresponding id values:

$user_id = 15;
$ids = array_map(function ($a) { return $a['id']; },
                 array_filter($array, 
                              function ($a) use ($user_id) {
                                  return $a['user_id'] == $user_id; 
                              })
                 );
print_r($ids);

Alternatively, you can use array_keys to search for the keys of the user_id values (extracted by array_column) which are 15 and use those keys in array_map to retrieve the id values:

$ids = array_map(function ($k) use ($array) { return $array[$k]['id']; },
                 array_keys(array_column($array, 'user_id'), $user_id)
                 );
print_r($ids);

In both cases the output (for your sample data) is:

Array
(
    [0] => 1
    [1] => 2
)

Demo on 3v4l.org

Just wanted to add an alternative answer. Although the array_ methods are handy, they also have downsides. In the other answer, the first method will process the array twice (once for the array_filter() and the result with the array_map()) and the second method will do this 3 times. This seems handy, but my alternative uses a simple foreach() loop. It makes 1 pass through the array and just checks the user_id and adds it to a list if it matches...

$ids = [];
foreach ( $array as $user ) {
    if ( $user['user_id'] == $user_id ) {
        $ids[] = $user['id'];
    }
}
print_r($ids);

which gives...

Array
(
    [0] => 1
    [1] => 2
)
Related