phparraysmultidimensional-arraygroupingsub-array

Group rows by one column and populate subarray within group with another column's value


I have an array coming from my database and simply it consists of questions and answers. I am trying to merge 2 arrays and create multidimensional array if values are more than one.

Array
(
    [0] => Array
        (
            [question_id] => 1
            [option_id] => 1
        )

    [1] => Array
        (
            [question_id] => 2
            [option_id] => 3
        )

    [2] => Array
        (
            [question_id] => 3
            [option_id] => 5
        )

    [3] => Array
        (
            [question_id] => 3
            [option_id] => 6
        )

)

I've tried to separate answers and questions to 2 different arrays but couldn't figure how to merge them again.

$user_questions = array_column($answers, 'question_id');
$user_answers = array_column($answers, 'option_id');

What I need is (question 3 has 2 answers) :

Array
(
    [1] => 1
    [2] => 3
    [3] => Array (5, 6)
)

Solution

  • You can group your data like this as you fetch the results from your query instead of processing it after the fact. To get the array you have now, you're currently doing something like this:

    while ($row = $stmt->someFetchMethod()) {
        $result[] = $row;
    }
    

    Instead, use the question id as the key in your result array, and append the option id to an array at that key.

    while ($row = $stmt->someFetchMethod()) {
        $result[$row['question_id']][] = $row['option_id'];
    }