How do I get the id as a key and the email as its value from a multidimensional array?

I have a multidimensional array as shown 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 result to be as an array in the form of id as key and email as its value.

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

      

I need a short code for this, No long code needed.

I tried it with foreach

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

      

Does anyone know a shortcode for this to fulfill my requirements.

+3


source to share


3 answers


I think you can try php in-build function to sort your solution

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

      



You can also refer to the following link.

PHP built-in function function (array_column)

+3


source


This should work for you:

Just a array_combine()

column id

with a column email

that you can grab with array_column()

.



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

      

+1


source


For compatibility reasons, since it 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 foreach

that, but that's a matter of personal taste.

0


source







All Articles