0

Possible Duplicate:
How do I sort a multidimensional array in php

Lets say i have following Multi-dimentional Array:

$fruits[] = array("name"=>"orange", "price"=>3, "code"=>"A45");
$fruits[] = array("name"=>"apple", "price"=>2, "code"=>"W71");
$fruits[] = array("name"=>"grape", "price"=>4, "code"=>"G11");

Then i wanted to sort this $fruits[] array by its price.
So it should be:

$fruits[] = array("name"=>"apple", "price"=>2, "code"=>"W71");
$fruits[] = array("name"=>"orange", "price"=>3, "code"=>"A45");
$fruits[] = array("name"=>"grape", "price"=>4, "code"=>"G11");

Then i surfed around web alot and finally i found following one from php manual (i adjusted the variable names with my array above):

// Obtain a list of columns
foreach ($fruits as $key => $value) {
    $name[$key]  = $value['name'];
    $price[$key] = $value['price'];
    $code[$key] = $value['code'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($price, SORT_ASC, $fruits);

OK, got it! Then the $fruits[] array is sorted by price values properly.
Well, here are some of my concerns:

  • As far as I've learned before, we should not add/use any additional/customized codes to use a Sorting Machinism. (Instead, i believe we should use pure Built-in Methods.)
  • Here I doubt the performance because it is having pre-custom foreach loop inside, which may dramatically bring down the speed while we are having real huge arrays. (like i have now)

So now what i want to ask is:

  • Does PHP has any pure Method to achieve this thing?
  • [or] Can't we just rectify this Multi-dimentional Array Sorting Issue by only using/picking from some of PHP pure built-in, array-sorting Methods (e.g: sort(), usort(), asort(), array_multisort(), etc..) ?
Community
  • 1
  • 1
夏期劇場
  • 15,969
  • 40
  • 121
  • 208

2 Answers2

2
usort ($fruits, function($a, $b) { return $a['price'] > $b['price'] ? 1 : ($a['price'] == $b['price'] ? 0 : -1); });
Barmar
  • 596,455
  • 48
  • 393
  • 495
0

usort sounds like what you're looking for:

<?
$fruits[] = array("name"=>"orange", "price"=>3, "code"=>"A45");
$fruits[] = array("name"=>"apple", "price"=>2, "code"=>"W71");
$fruits[] = array("name"=>"grape", "price"=>4, "code"=>"G11");
usort($fruits, function($a, $b){return $a['price'] - $b['price'];});
print_r($fruits);
?>

produces:

Array
(
    [0] => Array
        (
            [name] => apple
            [price] => 2
            [code] => W71
        )

    [1] => Array
        (
            [name] => orange
            [price] => 3
            [code] => A45
        )

    [2] => Array
        (
            [name] => grape
            [price] => 4
            [code] => G11
        )

)
adamdunson
  • 2,479
  • 1
  • 20
  • 27