如何在php中使用多次找到公共id的数组内部数组

时间:2016-06-15 07:12:20

标签: php arrays json

这就是我的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_idquestion相同,而answer_idanswer则不同。我需要一个没有question_idquestion的数组中的所有三个答案,就像一个有多个答案的问题。我试图在php中实现这一点。

1 个答案:

答案 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