我创建了一个数组,它可以容纳多个级别的'子'数组。
$this->project_tasks: Array
(
[0] => Array
(
[person_name] => User 1
[reports_to_id] =>
[task_id] => 1123
[task_name] => Main Task
[sub_task_id] => Array
(
[0] => Array
(
[person_name] => User 1
[reports_to_id] => 1123
[task_id] => 1124
[task_name] => sub Task 1-1
[sub_task_id] => Array
(
[0] => Array
(
[person_name] => User 1
[reports_to_id] => 1124
[task_id] => 1125
[task_name] => sub Task 1-1-1
)
)
)
[1] => Array
(
[person_name] => User 1
[reports_to_id] => 1123
[task_id] => 1127
[task_name] => sub Task 1-2
)
)
)
[1] => Array
(
[person_name] => User 1
[reports_to_id] =>
[task_id] => 1126
[task_name] => Main Task 2
)
)
创建数组没有问题,目前的问题是我如何以这样的方式迭代整个数据集:
1123 - Main Task
1124 - sub Task 1-1
1125 - sub Task 1-1-1
1127 - sub Task 1-2
...
1126 - Main Task 2
...
etc...
我找到了array_walk_recursive()但它不会做包含数组的键。此外,数组结构必须不关心递归的“深度”。可能是10级以上,无所谓。
非常感谢任何帮助。
答案 0 :(得分:0)
试试这段代码:
function customRecursiveWalk($array,$level){
$size = count($array);
for ($i=0;$i<$size;$i++) {
for ($j=0;$j<$level;$j++)
echo " "; //Print the indentation level
//Print the current task id and the task name
echo($array[$i]['task_id'] ." - ".$array[$i]['task_name']);
echo '<br/>';
//Call the recursive walk for the child
customRecursiveWalk($array[$i]['sub_task_id'],$level+1);
}
}
customRecursiveWalk($this->project_tasks,0);
答案 1 :(得分:-1)
我不知道完整的用例,但似乎一个简单的递归函数可以解决这个问题。我已经使用ul / li来建立多个级别,但这当然不是必需的 - 例如,我还包含了一个函数,它将为您提供一个包含按顺序列出的任务的平面数组。
首先,HTML版本:
function listTasks($list, $level=0) {
print '<li>'.$list['task_id'].' - '.$list['task_name'];
if (array_key_exists('sub_task_id', $list)) {
print '<br><ul>';
foreach ($list['sub_task_id'] as $subtasks) {
listTasks($subtasks, $level+1);
}
print '</ul>';
}
print '</li>';
}
print '<ul>';
foreach ($a as $tasks) {
listTasks($tasks, 1);
}
print '</ul>';
示例输出:
1123 - Main Task
1124 - sub Task 1-1
1125 - sub Task 1-1-1
1127 - sub Task 1-2
1126 - Main Task 2
生成一个平面阵列:
function listTasks($list, &$output, $level=0) {
$output[] = array(
'id'=>$list['task_id'],
'name'=>$list['task_name'],
'level'=>$level
);
if (array_key_exists('sub_task_id', $list)) {
foreach ($list['sub_task_id'] as $subtasks) {
listTasks($subtasks, $output, $level+1);
}
}
}
$output = array();
foreach ($a as $tasks) {
listTasks($tasks, $output);
}
输出:
Array
(
[0] => Array
(
[id] => 1123
[name] => Main Task
[level] => 0
)
[1] => Array
(
[id] => 1124
[name] => sub Task 1-1
[level] => 1
)
[2] => Array
(
[id] => 1125
[name] => sub Task 1-1-1
[level] => 2
)
[3] => Array
(
[id] => 1127
[name] => sub Task 1-2
[level] => 1
)
[4] => Array
(
[id] => 1126
[name] => Main Task 2
[level] => 0
)
)