0

How can I arsort the following array in PHP (by value)?

  $array = array
  (
    "pie" => array
                    (
                      "value" => "183"
                    ),
    "apple" => array
                    (
                      "value" => "032"
                    )
  );

How could I sort this array so when I would loop through it and output the code that it would show PIE on the tap and APPLE below? I know how to do it when it's just an array, but I find it difficult to do it whenever I put an array within an array.

Martin Dev
  • 67
  • 2
  • 8

1 Answers1

-1

Here was the original question.

How could I sort this array so when I would loop through it and output the code that it would show PIE on the tap and APPLE below?

 usort($array, function($a, $b) {
     return $a['value'] - $b['value'];
 });

This function should do it. If you need it reversed, just use function($b, $a).

The unknown factor was why he was asking for PIE first, then APPLE, but the sort field is the "value" field, not Pie and Apple. The solution is correct, but since it was unclear about the sort order, the values might have needed to be reversed. No problem - code given.

TBowman
  • 615
  • 4
  • 15
  • How do I use this precisely? Also, my list is extended to about 30 more arrays within the main array, how would I use it in this case? – Martin Dev Jul 06 '17 at 16:23
  • 30 more arrays meaning more like "apple" and "pie" still using "value" as the sort field? – TBowman Jul 06 '17 at 16:31
  • yeah, they're all in the same array, I just don't really know how I'd use the method you provided, could I just assign a variable to it? – Martin Dev Jul 06 '17 at 16:32
  • The function doesn't need to be "used" it simply sorts the array. You don't call it or assign it. You can read more about anonymous functions here: http://www.elated.com/articles/php-anonymous-functions/ – TBowman Jul 06 '17 at 16:42
  • Also, I still want to be able to have the other things within the array like 'material' and 'created'. – Martin Dev Jul 06 '17 at 16:44
  • Thanks, that last comment did the job, I was just doing random stuff, turned out I just had it reversed. – Martin Dev Jul 06 '17 at 16:50