我有如下数组:
Array
(
[0] => Array
(
[question_id] => 1
[question_title] => Q1
[child_question_id] => NULL
)
[1] => Array
(
[question_id] => 2
[question_title] => Q2
[child_question_id] => NULL
)
[2] => Array
(
[question_id] => 3
[question_title] => Q3
[child_question_id] => 4
)
[3] => Array
(
[question_id] => 3
[question_title] => Q3
[child_question_id] => 5
)
[4] => Array
(
[question_id] => 4
[question_title] => Q4
[child_question_id] => NULL
)
[5] => Array
(
[question_id] => 5
[question_title] => Q5
[child_question_id] => NULL
)
[6] => Array
(
[question_id] => 6
[question_title] => Q6
[child_question_id] => NULL
)
[7] => Array
(
[question_id] => 7
[question_title] => Q7
[child_question_id] => 6
)
)
并使用 PHP 我期望结果为:
Array
(
[0] => Array
(
[question_id] => 1
[question_title] => Q1
[child_question_id] => NULL
)
[1] => Array
(
[question_id] => 2
[question_title] => Q2
[child_question_id] => NULL
)
[2] => Array
(
[question_id] => 3
[question_title] => Q3
[children] => array(
[0] => Array
(
[question_id] => 4
[question_title] => Q4
)
[1] => Array
(
[question_id] => 5
[question_title] => Q5
)
)
)
[3] => Array
(
[question_id] => 7
[question_title] => Q7
[children] => array(
[0] => Array
(
[question_id] => 6
[question_title] => Q6
)
)
)
)
我尝试使用以下逻辑构建最终数组:
- 遍历数组以收集子 ID 和子数据
- 再次遍历数组并将项目子 id 与之前形成的子数组匹配,如果找到则创建子数组
你能帮我创造更好的解决方案吗?