phpcodeigniterpivotgroupingresultset

How to group (pivot) a CodeIgniter query result set data by a column


The first table:
question

The second table:
answer

I use them for my exam. For each question, I have 3 answers. My problem is how to fetch them together and after fetch I want to have an array like this:

[0]=>array(8) 
{
    ["question"]=>  string(13) "question test"
    ["name_id"]=>   string(1) "1"
    ["answer"]=>    string(1) "1"
    ["points"]=>    string(1) "1"
    ["answer"]=>    string(1) "2"
    ["points"]=>    string(1) "2"
    ["answer"]=>    string(1) "3"
    ["points"]=>    string(1) "3"
}

but because the key answer and points are same i get this after fetch :

[0]=>array(4) 
{
    ["question"]=>  string(13) "question test"
    ["name_id"]=>   string(1) "1"
    ["answer"]=>    string(1) "1"
    ["points"]=>    string(1) "1"
}   
[1]=>array(4) 
{
    ["question"]=>  string(13) "question test"
    ["name_id"]=>   string(1) "1"
    ["answer"]=>    string(1) "2"
    ["points"]=>    string(1) "2"
}   
[2]=>array(4) 
{
    ["question"]=>  string(13) "question test"
    ["name_id"]=>   string(1) "1"
    ["answer"]=>    string(1) "3"
    ["points"]=>    string(1) "3"
}

the query I write is:

select question , name_id , answer, points from question , answer where question.id_question = answer.id_aquestion

Is there any solution fetch them in one array not 3 array? (the framework I use: CodeIgniter)


Solution

  • You can't have the same key name with different values first of all. It will just overwrite the value... This is what you could do:

    foreach ($results as $rowKey => $rowVal) {
        $processedResults[0] = [
            "question" => $rowVal["question"],
            "name_id" => $rowVal["name_id"],
            "answer" . $rowKey => $rowVal["answer"],
            "points" . $rowKey => $rowVal["points"]
        ];
    }
    

    This way you'll get

    [0]=>array(x) 
    {
        ["question"] => string(13) "question test"
        ["name_id"] => string(1) "1"
        ["answer0"] => string(1) "1"
        ["points0"] => string(1) "1"
        ["answer1"] => string(1) "2"
        ["points1"] => string(1) "2"
        ["answer2"] => string(1) "3"
        ["points2"] => string(1) "3"
        ....
        ["answerx"] => string(1) "x"
        ["pointsx"] => string(1) "x"
    }