简体   繁体   English

如何合并PHP数组

[英]How to merge php array

PHP Original array is a two-dimensional array. PHP原始数组是一个二维数组。

I want to extract all the different value(the key name is parentMenu) to be a new two-dimensional array's key name 我想提取所有不同的值(键名是parentMenu)作为新的二维数组的键名

at the same time old array will be the new array's value 同时旧数组将是新数组的值

what and how should id do? id应该怎么做?

below is 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 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')
            )
);  
$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 更新:根据@Anyone的建议调整代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM