簡體   English   中英

按自定義順序對php數組進行排序

[英]Sort a php array in a custom order

我有一個名為“ car_owners”的表,它具有三列,稱為:

id  owner   cars
1   Greg    1
2   Gary    3
3   Aaron   2
4   Farb    3
5   REX     1
6   Fred    2

在以下代碼中,將其放入數組並打印:

$exc = $conn->prepare("SELECT name,state from current_state");
        $exc->execute();
            while($finalResult = $exc->fetch(PDO::FETCH_ASSOC))
             {
                        $tables[] = $finalResult;
             }
var_dump($tables);

一旦我將其放入一個數組中, 有沒有一種方法可以按自定義順序對其進行排序,因此我可以像下面這樣輸出:首先是擁有2輛車的所有者,然后是擁有1輛車且擁有3輛車的所有者

owner   cars
Aaron   2
Fred    2
Greg    1
REX     1
Farb    3
Gary    3

PS從表中執行此操作將無法正常工作,因為即時通訊在代碼上方使用了一個循環,使得無法從SQL進行操作,有人可以告訴我一種從php進行操作的方法

select * from your_table
order by case when cars = 2 then 1
              when cars = 1 then 2
              when cars = 3 then 3
              else 4
         end

如果您是從mysql表中准備的數組,則可以使用以下代碼-

$car_array=array(
    "Aaron"=>2,
    "Fred"=>2,
    "Greg"=>1,
    "REX"=>1,
    "Farb"=>3,
    "Gary"=>3,
    );

$sort_array=array("2","1","3");
$new_array=array();

foreach ($sort_array as $key => $value) 
{
    foreach ($car_array as $key1 => $value1) 
    {
        if ($value1 == $value ) 
            $new_array[$key1]=$value1;
    }   
}


print_r($new_array);

考慮通過sql本身對結果集進行排序。 @juergen提供的sql將達到目的。 我要在查詢中做的唯一更改是“在order by子句中添加所有者字段”。 考慮下面的代碼片段

select * from car_owners
order by (case when cars = 2 then 1
              when cars = 1 then 2
              when cars = 3 then 3
              else 4
         end), owner

這應該可以達到目的,並為您提供所需的結果集。

另外,如果您明確需要通過php對其進行排序,則可以使用php usort()函數並對數組進行排序,以編寫自定義函數。

僅使用PHP,您可以使用uksort函數通過用戶定義的比較函數對數組進行排序。 以下代碼需要$tables變量的副本。

<?php
$tables2=$tables;
uksort($tables2, function($r1, $r2) use ($tables) {
    return ($tables[$r1]["cars"]%3) < ($tables[$r2]["cars"]%3);
});
print_r($tables2);

您可以使用usort對值進行排序。 如果兩個所有者擁有相同數量的汽車,則也會按名稱排序。 我已經更改了SELECT語句以匹配給定的數據庫定義。

$exc = $conn->prepare("SELECT owner, cars from current_state");
$exc->execute();

while ($finalResult = $exc->fetch(PDO::FETCH_ASSOC))
{
    $tables[] = $finalResult;
}

usort(
    $tables,
    function($a, $b) {
        // If same number of cars, sort by name
        if ($a['cars'] == $b['cars']) return strcmp($a['owner'], $b['owner']);

        // If owner a has two cars, place before b
        if ($a['cars'] == 2) return -1;

        // If owner b has two cars, place below a
        if ($b['cars'] == 2) return 1;

        // Neither owner a nor owner b has two cars, sort by number of cars
        return ($a['cars'] < $b['cars']) ? -1 : 1;
    }
);

foreach ($tables as $row) {
    echo $row['owner'], ' => ', $row['cars'], PHP_EOL;
}

輸出:

Aaron => 2
Fred => 2
Greg => 1
REX => 1
Farb => 3
Gary => 3

暫無
暫無

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

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