【问题标题】:Return the highest value from model to view从模型返回最高值到视图
【发布时间】:2016-07-25 10:15:52
【问题描述】:

我想知道如何比较这两个输出http://prntscr.com/bx7ay9 并返回array 中最高的value

我的型号代码

$this->db->select('additional');
$this->db->from('order_detail');
$this->db->where('order_id',$id);
$query = $this->db->get();
foreach ($query->result() as $row)
{
   $return[] = $row->additional;
}
return $return;

【问题讨论】:

  • 对于这么小的输出示例,最好直接在这里写输出而不是发送屏幕截图。

标签: php codeigniter model-view-controller


【解决方案1】:

只需在查询中使用select_max 获取最高值并使用row() 获取单行而不使用foreach loop 作为

$this->db->select_max('additional AS max_value');
$this->db->from('order_detail');
$this->db->where('order_id', $id);
$query = $this->db->get();
$ret = $query->row();
return $ret->max_value;

【讨论】:

    【解决方案2】:
    $this->db->select('additional');
        $this->db->from('order_detail');
        $this->db->where('order_id',$id);
        $query = $this->db->get();
        foreach ($query->result() as $row)
        {
           $return[] = max($row->additional);
    
        }
        return $return;
    

    【讨论】:

      【解决方案3】:

      刚刚使用了 Codeigniter Query Bulder 类的select_max

      型号,

      public function get_max ($id){
      
          $this->db->select_max('additional');
          $this->db->where('order_id',$id);
          $query = $this->db->get('order_detail');
      
          return $query->row();
      }
      

      在控制器中,

      $max = $this->Model->get_max($id);
      echo $max['additional']; // Display and see the value. 
      

      【讨论】:

        【解决方案4】:

        如果您想获得最大数量,请使用select_max()

        $this->db->select_max('additional');
        $this->db->from('order_detail');
        $this->db->where('order_id',$id);
        $query = $this->db->get();
        if($query->num_rows()){// check if data is not empty
           return $query->row()->additional;
        }
        return false;// you can return false here
        

        并且如果您想获取结果数组以供其他用途,您可以在代码中使用max()$this->db->select('additional'); 来获取数组中的最大数量。

        【讨论】:

          猜你喜欢
          • 2013-05-11
          • 2019-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多