按自定义顺序按键排序数组

时间:2022-02-06 17:49:19

I have the following multidimensional array

我有以下多维数组

Array
(
    [June 2015] => Array
        (
            [LOW] => Array
                (
                    [0] => 160.50
                )

            [MEDIUM] => Array
                (
                    [0] => 0.00
                )

            [HIGH] => Array
                (
                    [0] => 60.80
                )

        )

    [July 2015] => Array
        (
            [MEDIUM] => Array
                (
                    [0] => 226.00
                )

            [HIGH] => Array
                (
                    [0] => 263.00
                )

            [LOW] => Array
                (
                    [0] => 121.96
                )

        )

)

I need to sort each of the inner arrays by their key so they are in the order LOW, MEDIUM, HIGH (the first is correct by chance).

我需要按其键排序每个内部数组,因此它们的顺序为LOW,MEDIUM,HIGH(第一个是偶然的正确)。

I tried the following code which I took and adjusted from here:

我尝试了以下代码,我从这里开始调整:

function cmp($a, $b){
        $a = preg_replace('@^(LOW|MEDIUM|HIGH) @', '', $a);
        $b = preg_replace('@^(LOW|MEDIUM|HIGH) @', '', $b);
        return strcasecmp($a, $b);
    }

    foreach($live_quotations as $exp_conversion_date => $Aconversion_likelihood){
        foreach($Aconversion_likelihood as $conversion_likelihood => $quotation_values){

            uksort($live_quotations[$exp_conversion_date], "cmp");

        }
    }

but this orders them as HIGH, MEDIUM, LOW (ascending alphabetical). It does not matter if I change the order in the cmp function they are always sorted this way. I don't think I'm understanding this uksort or cmp function correctly. Any help will be great!

但是这会将它们命令为HIGH,MEDIUM,LOW(按字母顺序排列)。如果我改变cmp函数中的顺序并不重要,它们总是以这种方式排序。我不认为我正确理解这个uksort或cmp函数。任何帮助都会很棒!

Thanks

谢谢

1 个解决方案

#1


1  

You could use the following comparison function:

您可以使用以下比较功能:

function cmp($a, $b) {
    $order = Array( 'LOW' => 0, 'MEDIUM' => 1, 'HIGH' => 2 );
    return $order[$a] - $order[$b];
}

Example of this code is here.

此代码的示例在此处。

#1


1  

You could use the following comparison function:

您可以使用以下比较功能:

function cmp($a, $b) {
    $order = Array( 'LOW' => 0, 'MEDIUM' => 1, 'HIGH' => 2 );
    return $order[$a] - $order[$b];
}

Example of this code is here.

此代码的示例在此处。