简体   繁体   English

Codeigniter $ query-> result()循环到关联数组

[英]Codeigniter $query->result() loop to associative array

I'm having trouble getting this loop to return all of the rows that I know mysql is generating in this query. 我无法获得此循环以返回我知道mysql在此查询中生成的所有行。 The objects in my javascript console are returning as I would like them to; 我的javascript控制台中的对象正在按照我的意愿返回; however, I'm only getting the last row from each unique $row->student_id . 但是,我只从每个唯一的$row->student_id获取最后一行。 I can tell that each unique row->student_id is being overwritten by the previous, but I'm not sure how else to do this logic. 我可以告诉每个唯一的row->student_id被前一个覆盖,但我不知道怎么做这个逻辑。

This is part of a Codeigniter model. 这是Codeigniter模型的一部分。 My controller is performing a json_encode function on this function, then I'm pulling this data into my view with jQuery $.ajax wired to a handlebars.js template. 我的控制器正在对这个函数执行json_encode函数,然后我将这些数据拉到我的视图中,jQuery $.ajax连接到handlebars.js模板。 I'm aware that I could use ember for data bindings, but that is beyond my expertise at this time. 我知道我可以使用ember进行数据绑定,但这超出了我的专业知识。

$query = $this->db->get();
    if ($query->num_rows() > 0) {

        $prev = null;
        foreach ($query->result() as $row) {

            if ($prev != $row->student_id) {
                $data[$row->student_id] = array(
                    'first' => $row->last_name,
                    'last' => $row->first_name);
                $data[$row->student_id]['dorc'] = array($row->debit_or_credit);
                $prev = $row->student_id;
            } else {
                $data[$row->student_id]['dorc'][] += $row->debit_or_credit;

            }
        }

        return $data;
    } else {
        return array();
    }`

Your second if condition is not correct. 你的第二个if条件不正确。 You should replace it by this : 你应该用这个替换它:

foreach ($query->result() as $row) {
    if (!isset($data[$row->student_id])) { // Creates the row if not exists
        $data[$row->student_id] = array(
                            'first' => $row->last_name,
                            'last' => $row->first_name);
    }

    if (!isset($data[$row->student_id]['dorc'])) { // Create the dorc key if not exists
        $data[$row->student_id]['dorc'] = array($row->debit_or_credit);
    } else { // if it exists, push the debit_or_credit row value
        $data[$row->student_id]['dorc'][] = $row->debit_or_credit;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM