0

I have a JSON file that I created, and I want to sort from the biggest price value.

JSON is like this:

[
  {
    "username": "elbugato",
    "sold": 19,
    "qmimi": 38.5
  },
  {
    "username": "Pablo",
    "sold": 12,
    "qmimi": 42
  },
  {
    "username": "Hqstuff",
    "sold": 0,
    "qmimi": "0"
  },
  {
    "username": "matchspamm3rs",
    "sold": 0,
    "qmimi": "0"
  },
  {
    "username": "Pachenko",
    "sold": 1,
    "qmimi": 1.1
  },

I want to sort qmimi from the highest value

My php code is this.

$sellertop8json = json_decode(get_html('link'));
$i = 1;
sort($sellertop8json->qmimi, SORT_NUMERIC);
foreach($sellertop8json as $top8){
max($top8);
        if (++$i == 8) break;


    echo '<tr>
    <td>'.$top8->username.'</td>
    <td># '.$top8->sold.'</td>
    <td>$ '.$top8->qmimi.'</td>
    </tr>
    ';


}

but they aren't sorting from the biggest value The results I get :

result

Look at "Pachenko", he is after a seller that has "0" Earned.

Thank You Sorry for my bad English

P.S : JSON ISN'T RAW, I copied from some extension I am using on google chrome, so JSON it's not the problem.

Ruslan Osmanov
  • 17,894
  • 7
  • 38
  • 53

1 Answers1

0

You need to use usort and provide custom function comparing the field of the element:

usort($sellertop8json, function($a, $b) {
           return $a->qmimi == $b->qmimi ? 0 :
                   $a->qmimi < $b->qmimi ? 1 : -1;
      }
);

The comparison function must return 0 if the elements are equal, less than 0 if the first element is lower and greater than 0 if the second element is higher.

This may be a bit confusing as you're sorting from highest and therefore the swap of the sign in comparison - see the last part of comparison.

Zbynek Vyskovsky - kvr000
  • 16,547
  • 2
  • 30
  • 40