这就是我的Array的样子:
(
[0] => stdClass Object
(
[question_id] => 2
[question] => Which career is help to achive mca?
[answer_id] => 1
[answer] => nmit bangalore is the best college ever for mca
)
[1] => stdClass Object
(
[question_id] => 2
[question] => Which career is help to achive mca?
[answer_id] => 6
[answer] => rnsit is the best college
)
[2] => stdClass Object
(
[question_id] => 2
[question] => Which career is help to achive mca?
[answer_id] => 7
[answer] => city college is best for mca
)
如果您看到前三组,则question_id
和question
相同,而answer_id
和answer
则不同。我需要一个没有question_id
和question
的数组中的所有三个答案,就像一个有多个答案的问题。我试图在php中实现这一点。
答案 0 :(得分:1)
您可以使用简单的foreach
循环逐步构建一个包含问题和关联答案的关联数组,如下所示:
// Declare $result_arr array to store the result array
$result_arr = array();
// Suppose $arr is your original array
foreach($arr as $obj){
$result_arr[$obj->question_id]['question_id'] = $obj->question_id;
$result_arr[$obj->question_id]['question'] = $obj->question;
$result_arr[$obj->question_id]['answers'][] = array('answer_id' => $obj->answer_id, 'answer' => $obj->answer);
}
$result_arr = array_values($result_arr);
echo "<pre>"; print_r($result_arr);
这里是live demo。