我的数组如下:
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
)
)
)
)
我尝试使用以下逻辑构建最终数组:
你能帮助我创造更好的解决方案吗?
答案 0 :(得分:0)
你的意思是什么?
$i = 0;
$new = array();
$unsetter = array();
foreach($array as $val)
{
$new[$i] = array();
foreach($val as $key => $data)
{
if(($key == 'child_question_id') && (!is_null($data)))
{
$new[$i]['children'] = array();
$new[$i]['children']['question_id'] = $data;
$new[$i]['children']['question_title'] = $array[$data]['question_title'];
$unsetter[] = $data;
} else {
$new[$i][$key] = $data;
}
}
$i++;
}
foreach($unsetter as $uns)
{
unset($new[$uns]);
}
$new = array_values($new);
var_dump($new);
这将输出
array (size=5)
0 =>
array (size=3)
'question_id' => int 1
'question_title' => string 'Q1' (length=2)
'child_question_id' => null
1 =>
array (size=3)
'question_id' => int 2
'question_title' => string 'Q2' (length=2)
'child_question_id' => null
2 =>
array (size=3)
'question_id' => int 3
'question_title' => string 'Q3' (length=2)
'children' =>
array (size=2)
'question_id' => int 4
'question_title' => string 'Q4' (length=2)
3 =>
array (size=3)
'question_id' => int 3
'question_title' => string 'Q3' (length=2)
'children' =>
array (size=2)
'question_id' => int 5
'question_title' => string 'Q5' (length=2)
4 =>
array (size=3)
'question_id' => int 7
'question_title' => string 'Q7' (length=2)
'children' =>
array (size=2)
'question_id' => int 6
'question_title' => string 'Q6' (length=2)