Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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.

like image 579
Weilory Avatar asked Dec 06 '25 14:12

Weilory


1 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

like image 95
Nick Avatar answered Dec 08 '25 05:12

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!