按键值对多维数组进行分组?

时间:2016-07-14 06:11:07

标签: php arrays multidimensional-array

  

我有一个多维数组,我试图根据键值对数组进行分组。

     

所以,我试图按键对它们进行分组,但我没有对它进行分组   基于键值的数组。

     

以下是原始数组

 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
                 )
          )

)

2 个答案:

答案 0 :(得分:2)

这是一个带有demo的解决方案。可以帮到你:

// $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);

点击此处查看Demo

答案 1 :(得分:1)

如果你的初始数组被称为$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);
}

Demo here