微信小程序中如何将一维数组按条件转换为二维数组?
发布网友
发布时间:2022-04-23 02:19
我来回答
共1个回答
热心网友
时间:2023-10-11 11:51
写个函数,也是来自于tp官方
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
// 创建Tree
$tree = array();
if(is_array($list)) {
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] =& $list[$key];
}
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
然后定义一维数组为$list,然后 print_r(list_to_tree($list,"id","parentsid","subnav"));追问这是个啥? 就搬过来了