1

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')
            )
);  
4

1 回答 1

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

更新:根据@Anyone 的建议调整代码

于 2013-04-10T08:00:12.480 回答