PHP排序對象值但保留原始相對順序 (PHP sort objects value but retain original relative order)


問題描述

PHP排序對象值但保留原始相對順序 (PHP sort objects value but retain original relative order)

我正在使用 usort 對對像數組進行排序,但實際上我希望它充當一種“分組依據”功能,而不會干擾行的原始相對順序。

假設我有這個:

MASTER_CODE, CONFIG_ITEM
foo1, opt_ray
foo2, opt_ray
foo1, opt_fah
foo2, opt_doe

根據該數據,對像數組是用匿名鍵構造的。也就是說,每一行都被解析為一個對象。將對象收集到一個數組中。

我要做的是按 MASTER_CODE 值對數組進行排序,但不打亂順序。

也就是說,最終的順序應該是:

MASTER_CODE, CONFIG_ITEM
foo1, opt_ray
foo1, opt_fah
foo2, opt_ray
foo2, opt_doe

我們不添加排序順序,因為數據來自外部來源。

我可以使用usort按主碼排序,但它搞砸了原來的相對順序。

<

參考解法

方法 1:

This is one option ‑ it's not the most elegant solution. It will take the unique values from the first column of your array (the one you want to filter by), sort that, then loop it and add entries from your original array with the same first value.

// Get an unique array of values to use for sorting
$sorting = array_unique(array_column($a, 0));
sort($sorting);

$sorted = [];
foreach ($sorting as $sortValue) {
    $sorted = array_merge(
        $sorted,
        array_filter(
            $a,
            function($row) use ($sortValue) {
                // Find values that have the same first value as each sort value
                return ($sortValue === $row[0]);
            }
        )
    );
}

Example

Note: This will work on PHP 5.5. Since you also tagged PHP 5.3, you may need to replace the array_column function. Try something like this:

$sorting = array_unique(array_map(function($row) { return $row[0]; }, $a));

(by Timscrowler)

參考文件

  1. PHP sort objects value but retain original relative order (CC BY‑SA 2.5/3.0/4.0)

#php-5.5 #PHP #Sorting #arrays #php-5.3






相關問題

當作為參數傳遞時,PHP 如何解釋和評估函數和匿名函數? (How does PHP interpret and evaluate function and anonymous function when passed as an argument?)

使用 symfony 時 PHP 5.5 無法識別服務器 (PHP 5.5 won't recognise server when using symfony)

升級到 PHP5.5 時 Wordpress 崩潰 (Wordpress crashes when upgrading to PHP5.5)

從數據庫返回多個值 (return multiple values from database)

PHP:嵌套 foreach 循環的問題 (PHP: Issue with nested foreach loops)

如果條件在幾小時、幾天內不起作用 (if condition not working for Hours,Days)

Slim 3.3 輸出中缺少字符 (Slim 3.3 missing characters in output)

PHP排序對象值但保留原始相對順序 (PHP sort objects value but retain original relative order)

遇到錯誤無法加載請求的文件:helpers/form_validation_helper.php (An Error Was Encountered Unable to load the requested file: helpers/form_validation_helper.php)

如何從類的函數內部訪問全局變量 (How to access global variable from inside class's function)

如何修改輸出緩衝區? (How to modify output buffer?)

在同一台 Ubuntu 服務器上安裝和配置 PHP5 和 7 (Install and configure PHP5 and 7 on same Ubuntu server)







留言討論