简体   繁体   中英

How to get id as key and email as its value from multidimensional array?

I have multi-dimensional array like below

$records = array(
    array(
        'id' => 11,
        'first_name' => 'John',
        'last_name' => 'Doe',
        'email' => 'john@gmail.com'
    ),
    array(
        'id' => 12,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
        'email' => 'sally@gmail.com'
    ),
    array(
        'id' => 13,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
        'email' => 'jane@gmail.com'
    )
);

Now,I want the output as array in form of id as key and email as its value.

Array
(
    [11] => john@gmail.com
    [12] => sally@gmail.com
    [13] => jane@gmail.com
)

I want short code for it, Not want any lengthy code.

I have tried it with foreach

$collect_data = array();
foreach($records as $key=>$data){
  $collect_data[$data['id']] = $data['email']
}

Any one know short code for above to achieve my requirement.

I think, You can try php in-build function to sort out your solution

$emails = array_column($records, 'email', 'id');
print_r($last_names);

You can also refer following link too.

Php In-build Function (array_column)

This should work for you:

Just array_combine() the id column with the email column, which you can grab with array_column() .

$collect_data = array_combine(array_column($records, "id"), array_column($records, "email"));

For compatibility sake, as array_column was introduced in PHP 5.5, consider array_reduce :

$output = array_reduce($records, function($memo, $item){
  $memo[$item['id'] = $item['email'];
  return $memo;
}, []);

I find it more expressive than a foreach , but that's matter of personal taste.

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