按列值排名对二维数组的行进行排序,然后按列值排序,然后按另一个列值排序

问题描述 投票:0回答:2

我有一个包含

floor
office
值的 MySQL 结果集。我想对行进行排序,以便首先显示最低楼层和办公室,并且在所有楼层的所有办公室中的最低楼层之前不会再次列出楼层

结果集数组示例:

$result = [
    ['floor' => 1, 'office' => 4],
    ['floor' => 1, 'office' => 5],
    ['floor' => 1, 'office' => 6],
    ['floor' => 2, 'office' => 4],
    ['floor' => 2, 'office' => 5],
    ['floor' => 2, 'office' => 6],
    ['floor' => 2, 'office' => 7],
    ['floor' => 3, 'office' => 3],
    ['floor' => 3, 'office' => 4],
    ['floor' => 3, 'office' => 5],
    ['floor' => 3, 'office' => 6],
    ['floor' => 3, 'office' => 7],
    ['floor' => 4, 'office' => 3],
    ['floor' => 4, 'office' => 4],
    ['floor' => 4, 'office' => 5],
    ['floor' => 4, 'office' => 6],
    ['floor' => 4, 'office' => 7]
];

我想要的结果

[
    ['floor' => '1', 'office' => '4'],
    ['floor' => '2', 'office' => '4'],
    ['floor' => '3', 'office' => '3'],
    ['floor' => '4', 'office' => '3'],
    ['floor' => '1', 'office' => '5'],
    ['floor' => '2', 'office' => '5'],
    ['floor' => '3', 'office' => '4'],
    ['floor' => '4', 'office' => '4'],
    ['floor' => '1', 'office' => '6'],
    ['floor' => '2', 'office' => '6'],
    ['floor' => '3', 'office' => '5'],
    ['floor' => '4', 'office' => '5'],
    ['floor' => '2', 'office' => '7'],
    ['floor' => '3', 'office' => '6'],
    ['floor' => '4', 'office' => '6'],
    ['floor' => '3', 'office' => '7'],
    ['floor' => '4', 'office' => '7'],
];

我需要做的是一次循环遍历每一层楼,并选择编号最低的办公室,然后再次从编号最低的楼层开始,直到筋疲力尽。

php arrays sorting multidimensional-array custom-sort
2个回答
1
投票

您可能想要的是

usort
功能。类似的东西

function racerCompare($a, $b) {
    if ($a['heat_nbr'] > $b['heat_nbr'}) {
        return -1;
    } else if ($a['heat_nbr'] < $b['heat_nbr'}) {
        return 1;
    } else {
        return 0;
    }
}
usort($startingArray, 'racerCompare');

racerCompare
逻辑可能有点不同(问题并不完全清楚)。


0
投票

编写 SQL 来生成已按

floor
排序的结果集,然后按
office
排序。然后使用
array_map()
为每个唯一楼层值创建一个递增计数器数组,从 1 开始。这意味着在
array_multisort()
排序时,所有计数器为 1 的楼层将排在前面,然后是所有计数器为 2 的行,等等 PHPize 演示

$sql = <<<SQL
SELECT *
FROM office_layout
ORDER BY floor, office
SQL;

$result = $mysqli->query($sql)->fetch_all(MYSQLI_ASSOC);

array_multisort(
    array_map(
        function ($row) {
            static $c;
            return $c[$row['floor']] = ($c[$row['floor']] ?? 0) + 1;
        },
        $result
    ),
    $result
);
var_export($result);

如果您的数据库版本支持窗口函数(MySQL8.0及更高版本),则更优雅的是,在SQL中完成整个操作。 PHPize 演示

$sql = <<<SQL
SELECT floor, office
FROM office_layout
ORDER BY 
    ROW_NUMBER() OVER (PARTITION BY floor ORDER BY office),
    floor,
    office;
SQL;

$result = $mysqli->query($sql)->fetch_all(MYSQLI_ASSOC);
var_export($result);
© www.soinside.com 2019 - 2024. All rights reserved.