【问题标题】:sort mysql rows by column?按列对mysql行进行排序?
【发布时间】:2014-03-12 18:12:56
【问题描述】:

我有以下 sql 查询:

SELECT job_id, job_type FROM jobs

我从 mysql 查询中得到以下结果(行集):

结果(打印_r):

Array
(
    [0] => stdClass Object
        (
            [job_id] => 239
            [job_type] => 'type1';
        }
    [1] => stdClass Object
        {
            [job_id] => 53
            [job_type] => 'type2';
        }
    [2] => stdClass Object
        {
            [job_id] => 76
            [job_type] => 'type3';
        }
    [3] => stdClass Object
        {
            [job_id] => 78
            [job_type] => 'type1';
        }       
)

如你所见,我有三种类型的工作:type1、type2、type3

有没有办法通过job_type 映射/重新组合这些结果? 基本上我想要类似的东西:

Array 
(
    ['type1'] => Array (
        [0] => stdClass Object 
            {
                [job_id] => 239
                [job_type] => 'type1';          
            }
        [1] => stdClass Object 
            {
                [job_id] => 76
                [job_type] => 'type1';          
            }           
    )

    ['type2'] => Array (
        [0] => stdClass Object 
            {
                [job_id] => 53
                [job_type] => 'type2';          
            }
    )

    ['type3'] => Array (
        [0] => stdClass Object 
            {
                [job_id] => 78
                [job_type] => 'type3';          
            }
    )
)

或者我应该使用不同的查询? 我试过使用array_map(),但没有成功,但我只得到了一个数组,其中的元素来自一个job_type。

提前致谢。

【问题讨论】:

  • 在查询末尾添加ORDER BY job_type
  • ORDER BY job_type 只会对我得到的行集进行排序 - 它不会将它们拆分为 job_type 的单独数组
  • 您可以根据类型的数量创建一个数组并遍历每个项目并将其添加到数组中,但我认为您的目标可能不是正确的做事方式跨度>

标签: php mysql arrays sorting


【解决方案1】:

您无法使用预定义的 PHP 函数执行此操作。但是你可以很容易地自己做。

例如:假设您将问题中写入的 MySQL 结果保存在名为 $rows 的变量中,您可以执行以下操作来获取所需的映射。

$map = array();
foreach($rows as $row) {
    if (!isset($map[$row->job_type])) {
        $map[$row->job_type] = array($row);
    } else {
        $map[$row->job_type][] = $row;
    }
}

现在 $map 包含您想要的数组。

【讨论】:

    【解决方案2】:

    不幸的是,这个任务在纯 PHP/MySQL 中没有原生解决方案。因此,您需要在 PHP 端手动对其进行排序。我认为您应该为此编写函数并在需要时使用它

    function sortBy($array, $key, $sortKeys=false){
       // I don't test this function, just write it for answer, so it may contain errors
       $tmp = array();
          foreach($array as $k=>$v){
              $tmp[$array[$k][$key]][] = $v;
          }
       if($sortKeys)
           ksort($tmp);
       return $tmp;
    }
    

    并像使用它一样

    print_r(sortBy(mySQLSelect(),'job_type'));
    

    【讨论】:

      猜你喜欢
      • 2013-09-08
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 2016-03-04
      • 2011-01-07
      • 1970-01-01
      • 2019-08-23
      相关资源
      最近更新 更多