在不使用循环的情况下,如何将一组关联数组“切”成单独的数组,按键分组?

时间:2021-01-03 12:48:00

Say I have the following array of associative arrays:

假设我有以下关联数组数组:

$MasterArr = array(
    array("food" => "apple", "taste" => "sweet"),
    array("food" => "lemon", "taste" => "sour"),
    array("food" => "steak", "taste" => "meaty")
);

Without using a foreach loop, is there a way that can I "chop" it into 2 different arrays whose values come from the same keys, so it looks like this:

如果不使用foreach循环,有没有办法可以将它“切”成2个不同的数组,其值来自相同的键,所以它看起来像这样:

$FoodArr = array("apple","lemon","steak");
$TasteArr = array("sweet","sour","meaty");

2 个解决方案

#1


4  

You can use array_column for that:

您可以使用array_column:

$FoodArr = array_column($MasterArr, 'food');
$TasteArr = array_column($MasterArr, 'taste');

#2


3  

For PHP < 5.5.0, you can use array_map:

对于PHP <5.5.0,您可以使用array_map:

$FoodArr = array_map(function($v){ return $v['food']; }, $MasterArr);
$TasteArr = array_map(function($v){ return $v['taste']; }, $MasterArr);

#1


4  

You can use array_column for that:

您可以使用array_column:

$FoodArr = array_column($MasterArr, 'food');
$TasteArr = array_column($MasterArr, 'taste');

#2


3  

For PHP < 5.5.0, you can use array_map:

对于PHP <5.5.0,您可以使用array_map:

$FoodArr = array_map(function($v){ return $v['food']; }, $MasterArr);
$TasteArr = array_map(function($v){ return $v['taste']; }, $MasterArr);