dongpou1935 2012-10-02 01:05
浏览 56
已采纳

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

I'm having trouble getting this loop to return all of the rows that I know mysql is generating in this query. The objects in my javascript console are returning as I would like them to; however, I'm only getting the last row from each unique $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.

This is part of a Codeigniter model. 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. I'm aware that I could use ember for data bindings, but that is beyond my expertise at this time.

$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();
    }`
  • 写回答

1条回答 默认 最新

  • doupu0619 2012-10-02 15:46
    关注

    Your second if condition is not correct. 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;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀