sort varchar column codeigniter

时间:2015-10-30 05:57:53

标签: php mysql codeigniter

我首先检查是否有任何像我一样的问题我找不到任何东西。 所有人都在排序与数字数据混合的字母数字列。

这是我的问题。 我有一个包含这样的A列数据的表。

  

WRG-01 WRG-39 WRG-22 WRG-45 WRG-43

需要将其排序为

  

WRG-01 WRG-22 WRG-39 WRG-43 WRG-45

这是我目前在codeigniter框架工作中使用的代码

$data['products'] = $this->db->order_by('product_id', 'asc')->get('products');
在mysql中我可以使用这个查询完成我的工作

preg_replace("/[^\d]/", "",'product_id'), 'asc')

如何将其应用于我的上述codeigniter代码?

这里是搜索功能

public function search()
{
    $data['title'] = 'Search Product';
    $product_name       = $this->input->get('product_name');
    $product_id         = $this->input->get('product_id');
    $product_category   = $this->input->get('product_category');
    $secondCategory     = $this->input->get('secondCategory');
    $thirdCategory  = $this->input->get('thirdCategory');

$data['category'] = $this->db->order_by('id', 'asc')->get_where('categories', ['parent' => 0]);
if($product_category != '')
{
    $data['secondCategory'] = $this->db->get_where('categories', ['parent' => $product_category]);
}
if($secondCategory != '')
{
    $data['thirdCategory'] = $this->db->get_where('categories', ['parent' => $secondCategory]);
}


if($product_name != '')
    {
        $this->db->like('product_name', $product_name);
    }
    if($product_id != '')
    {
        $this->db->where('product_id', $product_id);
    }
    if($product_category != '')
    {
        $this->db->where('product_category', $product_category);
    }
    if($secondCategory != '')
    {
        $this->db->where('secondCategory', $secondCategory);
    }
    if($thirdCategory != '')
    {
        $this->db->where('thirdCategory', $thirdCategory);
    }



    $data['products'] = $this->db->order_by('product_id' 'asc')->get('products');


    theme('all_product', $data);

}

我不能在这里使用sql查询,因为products是product table中的结果数组。

2 个答案:

答案 0 :(得分:3)

使用MySQL cast

cast(product_id as SIGNED)

cast(product_id as UNSIGNED)

尝试这样的查询: -

select * from products cast(product_id as UNSIGNED) ASC|DESC

答案 1 :(得分:0)

试试这个

$query= $this->db->query("SELECT * FROM products WHERE ??==?? ORDER BY product_id ASC");
$result= $query->result_array();
return $result;
  

默认数据将按升序

排序

这是在模型中。因此,如果将其传递给控制器​​,它将以 Objective Array 返回数据。

所以在控制器中你可以访问

$result = $this->model_name->method_for_above_code();
$name = $result[0]['name'];
$id = $result[0]['id'];

如果在视图中

$result['this_for_view'] = $this->model_name->method_for_above_code();
foreach ($this_for_view as $new_item) {
    echo "Name is ".$new_item['name'];
    echo "ID is ".$new_item['id'];
}