【问题标题】:Generating query result in for loop在for循环中生成查询结果
【发布时间】:2015-03-09 15:27:34
【问题描述】:

我想在 for 循环中生成一个查询,但我只得到第一个唯一 ID。我该如何解决这个问题?

观看次数

for ($i=0; $i < count($id); $i++) { 
    $id = $id[$i];
    $row = $get_cash_card->by_id($id);
    echo $row[0]['id'] . "<br/>";
}

型号:

    public function by_id($id)
    {
        $query = $query = $this->db->get_where('cash_cards_info', array('id' => $id));
        $rows  = $query->num_rows();
        return $query->result_array();
    }

控制器:

    public function cash_cards_on_hand_step1()
    {

            $this->load->model('cash_cards');

            $this->form_validation->set_rules('id', 'Cash Card', 'trim|required|xss_clean');

            $data['get_cash_card'] = $this->cash_cards;
            $data['id'] = $this->input->post('id');
            $data['main_content']  = 'cash_cards_on_hand_step1';

            $this->load->view('dashboard', $data);
    }   

它以 1 个唯一 ID 运行。有什么想法吗?

【问题讨论】:

  • 修改$id = $id[$i];到 $currentid = $id[$i];

标签: php mysql codeigniter for-loop


【解决方案1】:

您正在修改 $id 循环内的 for 变量。而不是这样做

for ($i=0; $i < count($id); $i++) { 
    $id = $id[$i];
    $row = $get_cash_card->by_id($id);
    echo $row[0]['id'] . "<br/>";
}

你需要做的

for ($i=0; $i < count($id); $i++) { 
    $newid = $id[$i]; //Change this line
    $row = $get_cash_card->by_id($newid);
    echo $row[0]['id'] . "<br/>";
}

因为您在第一次迭代时覆盖了$id 的值,这意味着您的for 循环中的$i &lt; count($id) 部分不再为真,因此循环停止。

另外你不应该在视图中访问你的模型,这是你应该在控制器中做的事情

【讨论】:

    【解决方案2】:

    这可能对你有用

    for ($i=0; $i < count($id); $i++) { 
    
        $row = $get_cash_card->by_id($id[$i]);
        echo $row[0]['id'] . "<br/>";
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      相关资源
      最近更新 更多