首頁  >  文章  >  後端開發  >  PHP數組多維排序實戰:從簡單到複雜場景

PHP數組多維排序實戰:從簡單到複雜場景

WBOY
WBOY原創
2024-04-29 21:12:02777瀏覽

多維數組排序可分為單列排序和巢狀排序。單列排序可使用 array_multisort() 函數依列排序;巢狀排序需要遞歸函數遍歷陣列並排序。實戰案例包括按產品名稱排序和按銷售量和價格複合排序。

PHP數組多維排序實戰:從簡單到複雜場景

PHP 陣列多維排序實戰:從簡單到複雜場景

引言

在PHP 中,對多維數組進行排序通常是一項複雜的任務。本教學將引導你逐步了解如何根據不同的場景進行多維數組排序,從簡單的單列排序到複雜的巢狀排序。

單列排序

最簡單的多維數組排序是根據單列進行排序。你可以使用array_multisort() 函數:

$arr = [
    ['id' => 1, 'name' => 'John Doe'],
    ['id' => 3, 'name' => 'Jane Smith'],
    ['id' => 2, 'name' => 'Bob Johnson'],
];

array_multisort(array_column($arr, 'id'), SORT_ASC, $arr);

print_r($arr);
// 输出:
// Array
// (
//     [0] => Array
//         (
//             [id] => 1
//             [name] => John Doe
//         )
//     [1] => Array
//         (
//             [id] => 2
//             [name] => Bob Johnson
//         )
//     [2] => Array
//         (
//             [id] => 3
//             [name] => Jane Smith
//         )
// )

#巢狀數組排序

對於巢狀數組,你需要使用遞歸函數來遍歷數組並對其進行排序:

function sortNestedArray($arr, $col, $order) {
    if (!is_array($arr)) {
        return $arr;
    }

    uasort($arr, function($a, $b) use ($col, $order) {
        if ($a[$col] == $b[$col]) {
            return 0;
        }

        return ($a[$col] < $b[$col]) ? -1 : 1;
    });

    foreach ($arr as &$item) {
        if (is_array($item)) {
            $item = sortNestedArray($item, $col, $order);
        }
    }

    return $arr;
}

實戰案例

案例1:依產品名稱對巢狀陣列進行排序

$products = [
    ['id' => 1, 'name' => 'Apple', 'price' => 10],
    ['id' => 2, 'name' => 'Orange', 'price' => 15],
    ['id' => 3, 'name' => 'Banana', 'price' => 5],
];

$sortedProducts = sortNestedArray($products, 'name', SORT_ASC);

// ... 处理排序后的数组 ...

案例2:以銷售量和價格對嵌套數組進行複合排序

$salesData = [
    ['product' => 'Apple', 'count' => 10, 'price' => 10],
    ['product' => 'Orange', 'count' => 15, 'price' => 15],
    ['product' => 'Banana', 'count' => 5, 'price' => 5],
];

usort($salesData, function($a, $b) {
    if ($a['count'] == $b['count']) {
        return ($a['price'] < $b['price']) ? -1 : 1;
    }

    return ($a['count'] < $b['count']) ? 1 : -1;
});

// ... 处理排序后的数据 ...

以上是PHP數組多維排序實戰:從簡單到複雜場景的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn