September 16, 2013

grouping multi-dimensional array in PHP

Devlin Carnate’s Question:

I have a multi-dimensional array, and I want to group it by org and then by dept. I have the first level of grouping working:

   $groups = array();
   foreach($inv_h as $item) {
       $groups[$item['org']][] = $item;
   }

How do I achieve the second level of grouping?

If thats how you are grouping the groups then:

   $groups = array();
   foreach($inv_h as $item) {
       $groups[$item['org']][] = $item;
   }

   $depts = array();
   foreach($inv_h as $item) {
       $depts[$item['org']][] = $item;
   }

   // Then combine these two array

   $merged = array_map(null, $groups, $depts); 

   // Now they are groups

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!