Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group array by subarray values

I have an array of subarrays in the following format:

array (     a => array ( id = 20, name = chimpanzee )     b => array ( id = 40, name = meeting )     c => array ( id = 20, name = dynasty )     d => array ( id = 50, name = chocolate )     e => array ( id = 10, name = bananas )     f => array ( id = 50, name = fantasy )     g => array ( id = 50, name = football ) ) 

And I would like to group it into a new array based on the id field in each subarray.

array (     10 => array           (             e => array ( id = 10, name = bananas )           )     20 => array           (             a => array ( id = 20, name = chimpanzee )             c => array ( id = 20, name = dynasty )           )     40 => array           (             b => array ( id = 40, name = meeting )           )     50 => array           (             d => array ( id = 50, name = chocolate )             f => array ( id = 50, name = fantasy )             g => array ( id = 50, name = football )           ) ) 
like image 426
Anson Kao Avatar asked Sep 27 '11 19:09

Anson Kao


People also ask

How do you group data in an array?

Steps to create the groupBy function, create an object as initial value for our result object. inside the array reduce, create an array for each distinct key value and push the currentValue if the key value present in the currentValue.

How to group array of array in JavaScript?

The group() method executes the callbackFn function once for each index of the array, returning a string (or value that can be coerced to a string) indicating the group of the element. A new property and array is created in the result object for each unique group name that is returned by the callback.

How to group by objects in JavaScript?

The most efficient method to group by a key on an array of objects in js is to use the reduce function. The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.


2 Answers

$arr = array();  foreach ($old_arr as $key => $item) {    $arr[$item['id']][$key] = $item; }  ksort($arr, SORT_NUMERIC); 
like image 191
Tim Cooper Avatar answered Sep 21 '22 10:09

Tim Cooper


foreach($array as $key => $value){    $newarray[$value['id']][$key] = $value; }  var_dump($newarray); 

piece of cake ;)

like image 44
amosrivera Avatar answered Sep 23 '22 10:09

amosrivera