使用codeigniter将数组推入现有数组?

时间:2012-08-10 16:09:29

标签: php arrays

我正在尝试将新数据推送到现有数组$query

$query = $this->db->get('questions');
foreach ($query->result_array() as $row) {

    $get_answers = $this->db->get_where('answers', array('question_id' => $row['question_id']), 4);
}
//push all the get_answers data into $query array as a subarray
return $query;

3 个答案:

答案 0 :(得分:1)

我认为你的$ query变量实际上并不是一个数组,而是一个结果集。你也应该把它放到一个数组中。也许是这样的:

$query = $this->db->get('questions');
$result_array = array();
$i = 0;
foreach($query->result_array() as $row){
    $result_array[$i] = $row;
    $result_array[$i]['answers'] = $this->db->get_where('answers', array('question_id'=>$row['question_id']), 4);
    $i++;
}

var_dump($result_array);

答案 1 :(得分:0)

使用array_merge()合并两个数组。

只需将其添加到$ query:

$query[] = $get_answers;

答案 2 :(得分:0)

这是你想要做的吗?

$query = $this->db->get('questions');
$answers = array();

foreach($query->result_array() as $row){
    $get_answers = $this->db->get_where('answers', array('question_id'=>$row['question_id']), 4);

    $answers[] = $get_answers;
}

然后,您可以将$answers[]附加到$query(顺便提一下,对于包含result s的变量,它是一个可怕的名称) array_merge()

$returnArray = array_merge($answers, $query);

return $returnArray;