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..) ?