多維數(shù)組排序可分為單列排序和嵌套排序。單列排序可使用 array_multisort() 函數(shù)按列排序;嵌套排序需要遞歸函數(shù)遍歷數(shù)組并排序。實戰(zhàn)案例包括按產(chǎn)品名稱排序和按銷售量和價格復(fù)合排序。
PHP 數(shù)組多維排序?qū)崙?zhàn):從簡單到復(fù)雜場景
引言
在 PHP 中,對多維數(shù)組進行排序通常是一項復(fù)雜的任務(wù)。本教程將引導(dǎo)你逐步了解如何根據(jù)不同的場景進行多維數(shù)組排序,從簡單的單列排序到復(fù)雜的嵌套排序。
立即學(xué)習(xí)“PHP免費學(xué)習(xí)筆記(深入)”;
單列排序
最簡單的多維數(shù)組排序是根據(jù)單列進行排序。你可以使用 array_multisort() 函數(shù):
$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 // ) // )
嵌套數(shù)組排序
對于嵌套數(shù)組,你需要使用遞歸函數(shù)來遍歷數(shù)組并對其進行排序:
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; }
實戰(zhàn)案例
案例 1:按產(chǎn)品名稱對嵌套數(shù)組進行排序
$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); // ... 處理排序后的數(shù)組 ...
案例 2:按銷售量和價格對嵌套數(shù)組進行復(fù)合排序
$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; }); // ... 處理排序后的數(shù)據(jù) ...
以上就是PHP數(shù)組多維排序?qū)崙?zhàn):從簡單到復(fù)雜場景的詳細內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
PHP怎么學(xué)習(xí)?PHP怎么入門?PHP在哪學(xué)?PHP怎么學(xué)才快?不用擔心,這里為大家提供了PHP速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://m.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號