【问题标题】:How to merge php array如何合并php数组
【发布时间】:2013-04-10 07:56:01
【问题描述】:

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

【问题讨论】:

  • 那么您付给开发人员多少钱来为您完成这项工作?
  • 听起来超级简单的任务。
  • @MarkBaker 我加入stackoverflow的时间不长,所以也谢谢你
  • 感谢各位朋友的帮助,问题已解决

标签: php arrays merge


【解决方案1】:
$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 的建议调整代码

【讨论】:

  • 我的声誉没有达到 15,我认为我需要为声誉工作
  • php.net/manual/en/function.array-push.php "注意:如果您使用 array_push() 向数组添加一个元素,最好使用 $array[] = 因为这样就没有调用函数的开销。"
猜你喜欢
  • 2010-09-06
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多