Given this array:
$inventory = array(
array(\"type\"=>\"fruit\", \"price\"=>3.50),
array(\"type\"=>\"milk\", \"price\"=>2.90),
array(\"
I ended on this:
function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}
array_multisort($sortarray, SORT_ASC, $array);
}
Just call the function, passing the array and the name of the field of the second level array. Like:
sort_array_of_array($inventory, 'price');
From Sort an array of associative arrays by value of given key in php:
by using usort (http://php.net/usort) , we can sort an array in ascending and descending order. just we need to create a function and pass it as parameter in usort. As per below example used greater than for ascending order if we passed less than condition then it's sort in descending order. Example :
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
usort($array, "cmp");
print_r($array);
Output:
Array
(
[0] => Array
(
[price] => 200.0
[product] => test3
)
[1] => Array
(
[price] => 1000.50
[product] => test1
)
[2] => Array
(
[price] => 8800.50
[product] => test2
)
)
try this:
$prices = array_column($inventory, 'price');
array_multisort($prices, SORT_DESC, $inventory);
print_r($inventory);
You might try to define your own comparison function and then use usort.
Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.
/**
* A method for sorting arrays by a certain key:value.
* SortByKey is the key you wish to sort by
* Direction can be ASC or DESC.
*
* @param $array
* @param $sortByKey
* @param $sortDirection
* @return array
*/
private function sortArray($array, $sortByKey, $sortDirection) {
$sortArray = array();
$tempArray = array();
foreach ( $array as $key => $value ) {
$tempArray[] = strtolower( $value[ $sortByKey ] );
}
if($sortDirection=='ASC'){ asort($tempArray ); }
else{ arsort($tempArray ); }
foreach ( $tempArray as $key => $temp ){
$sortArray[] = $array[ $key ];
}
return $sortArray;
}
to change the method to sort objects simply change the following line:
$tempArray[] = strtolower( $value[ $sortByKey ] );
to
$tempArray[] = strtolower( $value->$sortByKey );
To run the method simply do
sortArray($inventory,'price','ASC');
//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);
//result
Array
(
[2] => Array
(
[type] => pork
[price] => 5.43
)
[0] => Array
(
[type] => fruit
[price] => 3.5
)
[1] => Array
(
[type] => milk
[price] => 2.9
)
)