使用Codeigniter在PHP中构建数组

时间:2016-08-10 13:19:59

标签: php arrays codeigniter loops codeigniter-3

我正在尝试在Codeigniter 3中构建一个数组,但我似乎无法正确构建它。

我有2张桌子,我基本上需要结合;问题及其相关答案。

所以,基本上我需要一个多维数组,每个内部数组都包含问题数据及其相关的答案数据。

这就是我现在正在做的事情:

$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;

但是这会将每个问题作为一个数组单独输出,以及每个答案,我需要以某种方式将它们组合起来。这就是我得到的:

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"
}

这就是我需要的:

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"
}

我尝试过像array_push这样的东西,但我似乎无法让它工作?

我能尝试什么想法?

2 个答案:

答案 0 :(得分:2)

最简单的方法是创建一个包含所需内容的新数组,然后将其附加到$question_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;
}

答案 1 :(得分:0)

我认为这应该有用。

$question_array = array();

$i = 0;
foreach($course_object->result() as $question){

    $question_array[$i] = 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[$i]['answer'][] = $answer->answer;
        $question_array[$i]['result'][] = $answer->result;
    }

    $i++;
}

return $question_array;