我有一个多维数组,我正在尝试根据键值对数组进行分组。
所以,我正在尝试按键对它们进行分组,但我无法对 基于键值的数组。
下面是原始数组
Array
(
[0] => Array
(
[User] => Array
(
[id] => 2
[feature] => AddUser
[feature_level] => 1
[parent_feature] => 1
)
)
[1] => Array
(
[User] => Array
(
[id] => 3
[feature] => EditUser
[feature_level] => 1
[parent_feature] => 1
)
)
[2] => Array
(
[Candidate] => Array
(
[id] => 5
[feature] => AddCandidate
[feature_level] => 1
[parent_feature] => 4
)
)
[3] => Array
(
[Candidate] => Array
(
[id] => 6
[feature] => EditCandidate
[feature_level] => 1
[parent_feature] => 4
)
)
)
我需要的是
Array (
[User] => Array (
[0] => Array (
[id] => 2
[feature] => AddUser
[feature_level] => 1
[parent_feature] => 1
)
[1] => Array (
[id] => 3
[feature] => EditUser
[feature_level] => 1
[parent_feature] => 1
)
)
[Candidate] => Array (
[0] => Array (
[id] => 5
[feature] => AddCandidate
[feature_level] => 1
[parent_feature] => 4
)
[1] => Array (
[id] => 5
[feature] => EditCandidate
[feature_level] => 1
[parent_feature] => 4
)
)
)
这是一个带有演示的解决方案。可能会帮助您:
// $myArr is your origional array.
$result_arr = [];
array_walk($myArr,function($v,$k) use (&$result_arr){
$result_arr[key($v)][] = $v[key($v)];
});
print_r($result_arr);
点击这里观看演示
如果你的初始数组被称为 $source
,这应该可以做到:
$result =[]; //final array
foreach($source as $data){
$type = key($data); //eg: 'Candidate' or 'User'
if(!isset($result[$type])) $result[$type]=[];
$result[$type][] = reset($data);
}
在这里演示