如何从多维数组中获取id作为键和电子邮件作为其值?

时间:2020-11-29 23:47:17

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.

现在,我想将输出作为数组以id的形式作为键,并将电子邮件作为其值。

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

我用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.

任何人都知道上面的短代码来达到我的要求。

3 个解决方案

#1


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

我想,您可以尝试使用php in-build功能来解决您的解决方案

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

You can also refer following link too.

您也可以参考以下链接。

Php In-build Function (array_column)

Php内置函数(array_column)

#2


This should work for you:

这应该适合你:

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

只需array_combine()id列和email列,您可以使用array_column()获取该列。

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

#3


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

为了兼容性,在PHP 5.5中引入了array_column,请考虑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.

我发现它比foreach更具表现力,但这是个人品味的问题。

#1


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

我想,您可以尝试使用php in-build功能来解决您的解决方案

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

You can also refer following link too.

您也可以参考以下链接。

Php In-build Function (array_column)

Php内置函数(array_column)

#2


This should work for you:

这应该适合你:

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

只需array_combine()id列和email列,您可以使用array_column()获取该列。

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

#3


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

为了兼容性,在PHP 5.5中引入了array_column,请考虑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.

我发现它比foreach更具表现力,但这是个人品味的问题。