按特定索引降序对数组数组进行排序

时间:2017-12-12 21:19:54

标签: php arrays

我有下面的数组

Array
(
  [Prod1] => Array
    (
        [0] => $1,167,788.03
        [1] => 26,872
        [2] => 73.42
        [3] => 19.0%
        [4] => $1,134,106.83
        [5] => $1,681,843.02
        [6] => $3,098.65
        [7] => $42.20
        [8] => $-19.55
        [9] => $-9.60
        [10] => $43.46
        [11] => 0.97
    )

[Prod2] => Array
    (
        [0] => $6,730.84
        [1] => 161
        [2] => 0.44
        [3] => 13.7%
        [4] => $4,783.41
        [5] => $6,755.61
        [6] => $13.07
        [7] => $29.71
        [8] => $-27.30
        [9] => $-21.50
        [10] => $41.81
        [11] => 0.71
    )

[Prod3] => Array
    (
        [0] => $2,498,984.47
        [1] => 30,409
        [2] => 83.08
        [3] => 21.5%
        [4] => $3,026,866.16
        [5] => $3,850,645.25
        [6] => $8,270.13
        [7] => $99.54
        [8] => $-21.33
        [9] => $-8.19
        [10] => $82.18
        [11] => 1.21
    )
}

我试图根据索引[0]按降序排序,并尝试使用不同的PHP内置函数,但我没有成功。

基本上,期望的结果将按照以下顺序Prod3,Prod1,Prod2。

解决此问题的最佳方式是什么?

由于

2 个答案:

答案 0 :(得分:0)

我不知道usort是否是最佳方式,但用户功能相当简单:

usort($array, function ($a, $b) {
 $x = (int)str_replace(['$',',','.'],'',$a[0];
 $y = (int)str_replace(['$',',','.'],'',$b[0];
 if ($x === $y) return 0;
 return ($x < $y) ? 1 : -1;
});

编辑:我第一次错过了这些值的格式。如果没有Mohamad Attat的答案,我就不会发现它。 str_replace调用应该修复它,如果你的美元金额总是有两位小数。

答案 1 :(得分:0)

假设$ arr是您在上面显示的数组,下面的代码应该适用于您的情况

$tmp_arr = array();
$sorted_arr = array();
foreach ($arr as $key => $val_array) {
    //removing $ and ,
    $first_index_without_dollar = str_replace(array("$", ","), array("", ""), $val_array[0]);
    //getting string as number in order to sort
    $first_index_without_dollar = number_format((float) $first_index_without_dollar, 2, '.', '');
    $tmp_arr[$first_index_without_dollar] = $key;
}
//sorting by key descending
krsort($tmp_arr);

foreach ($tmp_arr as $val) {
    $sorted_arr[$val] = $arr[$val];
}