簡體   English   中英

按列排序mysql行?

[英]sort mysql rows by column?

我有以下SQL查詢:

SELECT job_id, job_type FROM jobs

我從mysql查詢中得到以下結果(行集):

結果(print_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';
        }       
)

如您所見,我有三種類型的工作: type1type2type3

有什么方法可以按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中獲取一個只有元素的數組。

提前致謝。

您不能使用預定義的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包含所需的數組。

不幸的是,此任務在純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'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM