frobak frobak - 3 months ago 51
PHP Question

Building an array in PHP with Codeigniter

I'm trying to build an array in Codeigniter 3, but I cant seem to structure it properly.

I have 2 tables that I basically need to combine; questions and their associated answers.

SO, basically I need a multidimensional array, each inner array is to contain the question data along with its associated answer data.

This is what I'm doing at the moment:

$question_array = array();

foreach($course_object->result() as $question){

$question_array[] = array (
'question_id' => $question->question_id,
'question' => $question->question,
);

$answer_data = $this->get_answer_data($question->question_id);

foreach($answer_data as $answer){
$question_array[]['answer'] = $answer->answer;
$question_array[]['result'] = $answer->result;
}
}

return $question_array;


But that outputs each question as an array on its own, as well as each answer, i need to combine them somehow. This is what I'm getting:

array(2) {
["question_id"]=>
string(3) "548"
["question"]=>
string(29) "Who enforces fire safety law?"
}

array(1) {
["answer"]=>
string(11) "The Manager"
}

array(1) {
["result"]=>
string(1) "0"
}



array(1) {
["answer"]=>
string(18) "The Fire Authority"
}


array(1) {
["result"]=>
string(1) "1"
}


and this is what i need:

array(2) {
["question_id"]=>
string(3) "548"
["question"]=>
string(29) "Who enforces fire safety law?"
["answer"]=>
string(11) "The Manager"
["result"]=>
string(1) "0"
["answer"]=>
string(18) "The Fire Authority"
["result"]=>
string(1) "1"
}


I've tried things like array_push but I cant seem to get it to work?

Any ideas what I can try?

Answer

The easiest way to do it is to create a new array with what you need, and append it to the $question_array, like this. You'll need a new subarray for the answers, because you can't have duplicate keys in an array.

foreach($course_object->result() as $question){

    $q_array = array (
        'question_id' => $question->question_id,
        'question'    => $question->question,
        'answers'     => array()
    );

    $answer_data = $this->get_answer_data($question->question_id);

    foreach($answer_data as $answer){
        $q_array['answers'][] = array(
            'answer' => $answer->answer,
            'result' =>$answer->result
        );
    }
    $question_array[] = $q_array;
}
Comments