php array sorting order by code example
Example 1: quick sort php
<?php
function quick_sort($my_array)
{
$loe = $gt = array();
if(count($my_array) < 2)
{
return $my_array;
}
$pivot_key = key($my_array);
$pivot = array_shift($my_array);
foreach($my_array as $val)
{
if($val <= $pivot)
{
$loe[] = $val;
}elseif ($val > $pivot)
{
$gt[] = $val;
}
}
return array_merge(quick_sort($loe),array($pivot_key=>$pivot),quick_sort($gt));
}
Example 2: sort array php
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
c = apple
b = banana
d = lemon
a = orange
Example 3: sort json in php
<?php
usort($data, function($a, $b) {
return $a->score > $b->score ? -1 : 1;
});
print_r($data);
?>