按照自定义顺序对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

p.S从表中进行操作是行不通的,因为我在代码上方使用循环,这使得无法从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

您可以使用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

如果您已经从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对其进行排序,那么您可以使用phpusort()函数并编写自定义函数对数组进行排序。

仅使用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);