【问题标题】:codeigniter fetch mysql table with where_in + keep order of key array in result arraycodeigniter 使用 where_in 获取 mysql 表 + 在结果数组中保持键数组的顺序
【发布时间】:2017-12-13 11:13:58
【问题描述】:

我有一个带有图像 ID 的字符串(从另一个 mysql 表中获取) 并转换为数组:

$idstring = "12, 18, 3, 392, 0, 9, 44";
$idarray = explode(',', $idstring);

基于这个 id 数组,我想从我的“媒体”mysql 表中获取所有行。

$result = $this->db->select('*')
->from('media')
->where_in('id', $ids)
->get()->result_array();

问题是$result 数组的值的顺序很奇怪,如下所示:

$result's order : 44, 9 ,0 ,18 ,3 ,392 ,12 ...

但我需要它们保持在我的 $id 字符串/数组顺序中...

到目前为止,我已经尝试了 4 种方法来解决这个问题:

  1. 在没有where_in() 的情况下循环获取行——这会产生很多查询——但现在可以使用......

  2. 根据$idstring$idarray 的顺序对$result 数组重新排序,尽管我无法找到工作结果,我不明白为什么要执行此步骤完全有必要

  3. 尝试修复查询本身。我听说过ORDER_BYFIND_IN_SET$ids,但我无法将其放入我的工作代码点火器查询中,并且不知道性能是否真的有帮助

所以总而言之,我认为这应该是一项简单的日常任务,我只想用 codeigniter 按给定顺序获取一堆图片。

我在这里缺少一个简单的解决方案吗?

【问题讨论】:

    标签: php mysql arrays codeigniter


    【解决方案1】:

    使用mysql的Field()函数

    $result = $this->db->select('*')
                ->from('media')
                ->where_in('id', $ids)
                ->order_by("FIELD(id,".join(',',$ids).")")
                ->get()
                ->result_array()
    

    应该是这样的

    FIELD(id,12, 18, 3, 392, 0, 9, 44)
    

    Reference

    Field() 返回逗号分隔列表的索引位置

    【讨论】:

    • $idstring 可以用来代替join(',',$idarray)
    • @PhilippMaurer 我猜这个"FIELD(id,".$idstring.")"会工作,如果你想用$idstring做的话
    • 非常感谢 philipp 和 m khalid junaid。我得到了它的工作 - 并学到了一些新东西。我的直觉是对的——一定有一个简单的方法:)
    【解决方案2】:

    接受的答案应该是M Khalid Junaid 的答案。但以防万一,如果您像我一样从数组生成,请像这样使用它:

    $filters = [
       "order_by" => [
           "title" => "DESC",
           ""FIELD(id,".join(',',$ids).")" => "" // The option should be empty...
       ]
    ];
    
    foreach($filters["order_by"] as $attribute => $option){
        $this->db->order_by( $attribute, $option );
    }
    

    输出将是:

    ...
    ORDER BY `name` DESC, FIELD(id, 2017, 2031, 2032, 2034, 2035)
    LIMIT 50 
    

    只是为了澄清。

    【讨论】:

      猜你喜欢
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多