Liuqing Hu
Liuqing Hu

Reputation: 1980

Group rows of a 2d array by a column and push rows as subarrays of each group

My original array is a two-dimensional array.

I want to extract all the different value (the key name is parentMenu) to be a new two-dimensional array's key name.

At the same time, the old array will be the new array's value

What should I do and how?

Below is an array example.

//the menuList is get from mysql result
$menuList = array(
0=>array(
  'navId' =>1,
  'parentMenu' =>  'HOME',   //Previous Menu
  'subMenu' =>  'SHOW USER', //Sub Menu
  'ctrl' =>  'Index',
  'action' =>  'index'
),
1=>array(
  'navId' =>2,
  'parentMenu' =>  'HOME',
  'subMenu' =>  'MODIFY PASSWORD',
  'ctrl' =>  'Modify',
  'action' =>  'index'
),
2=>array(
  'navId' =>3,
  'parentMenu' =>  'ITEM LIST',
  'subMenu' =>  'CURRENT LIST',
  'ctrl' =>  'Current',
  'action' =>  'index'
 ),
3=> array(
  'navId' =>4,
  'parentMenu' =>'ITEM LIST',
  'subMenu' =>'HISTORY LIST',
  'ctrl' =>'History',
  'action' =>'index'
  )
);

After processing the menuList, the new MenuList that I want is like below.

$newMenu = array(
    /*parentMenu's value to be key*/
    'HOME' => array(
        array('navId' => 1,'subMenu' => 'SHOW USER'    ,'ctrl' =>'Index', 'action' => 'index'),
        array('navId' => 2,'subMenu' => 'MODIFY PASSWORD','ctrl' => 'Modify'    ,'action' => 'index')
    ),
    'ITEM LIST' => array(
        array('navId' => 3,'subMenu' => 'CURRENT LIST','ctrl' => 'Current', 'action' =>'index'),
        array('navId' => 4, 'subMenu' => 'HISTORY LIST', 'ctrl' => 'History', 'action' => 'index')
    )
);

Upvotes: 1

Views: 123

Answers (1)

Raptor
Raptor

Reputation: 54212

$newMenu = array();
foreach($menuList as $item) {
  $key = $item['parentMenu'];
  unset($item['parentMenu']); // remove the parentMenu
  if(!isset($newMenu[$key])) {
    $newMenu[$key]] = array($item);
  } else {
    //array_push($newMenu[$key], $item);
    $newMenu[$key][] = $item;
  }
}

UPDATE: adjusted codes according to @Anyone's suggestion

Upvotes: 2

Related Questions