PHP数组如何其中相同的cid转换并且加新字段new二维数组?
程序员文章站
2022-05-11 16:49:30
...
数组:
Array
(
[0] => Array
(
[id] => 1
[menu_collapse] => 超级菜单
[menu_items] => 写文章
[cid] => 1
)
[1] => Array
(
[id] => 2
[menu_collapse] => 维护菜单
[menu_items] => 管理数据
[cid] => 2
)
[2] => Array
(
[id] => 3
[menu_collapse] => 维护菜单
[menu_items] => 管理用户
[cid] => 2
)
)
如何把上面数组转换这样的?
Array
(
[0] => Array
(
[id] => 1
[menu_collapse] => 超级菜单
[menu_items] => 写文章
[cid] => 1
)
[1] => Array
(
[new] => Array
(
[id] => 2
[menu_collapse] => 维护菜单
[menu_items] => 管理数据
[cid] => 2
)
(
[id] => 2
[menu_collapse] => 维护菜单
[menu_items] => 管理数据
[cid] => 2
)
)
回复内容:
数组:
Array
(
[0] => Array
(
[id] => 1
[menu_collapse] => 超级菜单
[menu_items] => 写文章
[cid] => 1
)
[1] => Array
(
[id] => 2
[menu_collapse] => 维护菜单
[menu_items] => 管理数据
[cid] => 2
)
[2] => Array
(
[id] => 3
[menu_collapse] => 维护菜单
[menu_items] => 管理用户
[cid] => 2
)
)
如何把上面数组转换这样的?
Array
(
[0] => Array
(
[id] => 1
[menu_collapse] => 超级菜单
[menu_items] => 写文章
[cid] => 1
)
[1] => Array
(
[new] => Array
(
[id] => 2
[menu_collapse] => 维护菜单
[menu_items] => 管理数据
[cid] => 2
)
(
[id] => 2
[menu_collapse] => 维护菜单
[menu_items] => 管理数据
[cid] => 2
)
)
$arr = [
['id' => 1,
'menu_collapse' => '超级菜单',
'menu_items' => '写文章',
'cid' => 1,
],
[ 'id' => 2,
'menu_collapse' => '维护菜单',
'menu_items' => '管理数据',
'cid' => 2,
],
[ 'id' => 3,
'menu_collapse' => '维护菜单',
'menu_items' => '管理用户',
'cid' => 2,
]
];
$result=[];
$res=[];
foreach($arr as $k=>$v){
$result[$v['cid']][]=$v;
}
foreach($result as $key=>$value){
if(count($value) == 1) {
$res[$key]=$value[0];
} else{
$res[$key]['new']=$value;
}
}
echo '';print_r(array_values($res));
/*
Array
(
[0] => Array
(
[id] => 1
[menu_collapse] => 超级菜单
[menu_items] => 写文章
[cid] => 1
)
[1] => Array
(
[new] => Array
(
[0] => Array
(
[id] => 2
[menu_collapse] => 维护菜单
[menu_items] => 管理数据
[cid] => 2
)
[1] => Array
(
[id] => 3
[menu_collapse] => 维护菜单
[menu_items] => 管理用户
[cid] => 2
)
)
)
)
*/
你只能遍历数组来处理了。