-1

I have the array below

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
    )
}

I am trying to sort it on descending order based of the index[0] and tried using different PHP built in functions but I was not successful on that.

Basically the desired result would be in the following order Prod3, Prod1, Prod2.

What would be the best way for solution for this?

Thanks

comsci_dude
  • 194
  • 2
  • 13

2 Answers2

0

I don't know if usort is the best way but the user function is fairly simple:

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;
});

Edit: I missed the format on the values the first time. And I would not have found it without Mohamad Attat's answer. The str_replace calls should fix it, iff you always have two decimals in your dollar amounts.

jh1711
  • 2,288
  • 1
  • 12
  • 20
0

supposing $arr is the array you've displayed above, the below code should work in your case

$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];
}
Att3t
  • 466
  • 2
  • 8