0015 0015 - 4 months ago 8
PHP Question

Group a multidimensional array by a Key value?


I have an multi dimensional array i am trying to group the array based on the key value.

So, I'm trying to group them by key but i am not getting to group the
array based on the key values.

Below is the original 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
)

)

)



What i need is


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

)

Ali Ali
Answer

Here is a solution with demo. Might help you:

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

Click Here for Demo