如何合并php数组

时间:2013-04-10 07:56:02

标签: php arrays merge

PHP原始数组是一个二维数组。

我想将所有不同的值(键名称为parentMenu)提取为新的二维数组的键名

同时旧数组将是新数组的值

id应该做什么以及如何做?

下面是数组示例

//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 what 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')
            )
);  

1 个答案:

答案 0 :(得分:2)

$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;
  }
}

更新:根据@任何人的建议调整代码