我想为这个查询使用数组创建一个新的数据结构,它将是:
将以查询和代码示例
开头query http://img85.imageshack.us/img85/170/query.png 我想为这个查询使用数组创建一个新的数据结构,它将像:
//this is for the first headline
[46] => Array
(
[headline_name] => headline 1
[score] => 50
[questions] => Array
(
[0] => Array
(
[question_id] => 136
[question_name] => question 3 , headline 1
[choice_0] => 0
[choice_1] => 0
[choice_2] => 0
[choice_3] => 0
[choice_4] => 0
) ,
[1] => Array
(
....
)
)
)
我写的想要实现这个结果的代码是:
foreach ($result as $row) {
$data[$row->headline_id]= array(
'headline_name' => $row->headline_name ,
'score' => $row->score,
);
$data[$row->headline_id]['questions'][] = array (
'question_id'=>$row->question_id ,
'question_name'=>$row->question_name ,
'choice_0' => $row->choice_0 ,
'choice_1' => $row->choice_1 ,
'choice_2' => $row->choice_2 ,
'choice_3' => $row->choice_3 ,
'choice_4' => $row->choice_4
);
}
它的问题,它只显示每个标题中的最后一个问题,在问题数组中的每个循环中,数组都没有附加,它们会相互覆盖
如果我想让它工作我必须删除我必须删除分数和headline_name的行,代码将是这样的
foreach ($result as $row) {
$data[$row->headline_id]['questions'][] = array (
'question_id'=>$row->question_id ,
'question_name'=>$row->question_name ,
'choice_0' => $row->choice_0 ,
'choice_1' => $row->choice_1 ,
'choice_2' => $row->choice_2 ,
'choice_3' => $row->choice_3 ,
'choice_4' => $row->choice_4
);
}
我想要一个解决方案,通过在数组
中编写headline_name和得分来解决它答案 0 :(得分:2)
问题是当你进入循环时第二次重置数组
按=
,
解决它你需要添加一点if
if(!isset($data[$row->headline_id])) {
$data[$row->headline_id]= array(
'headline_name' => $row->headline_name ,
'score' => $row->score,
);
}
另一个问题: 我建议不要在此表中存储此字段 没有正常化,
headline_name
score