Array opareas
(
[0] => Array
(
[name] = => array('opname1')
[subcats] => Array
(
[0] => Array
(
[amount] => 9883
[perc] => 112.61394712853236
)
[1] => Array
(
[amount] => 1
[perc] => 0.011394712853236098
)
[2] => Array
(
[amount] => 3679
[perc] => 41.921148587055605
)
)
)
[1] => Array
(
[name] = => array('opname2')
[subcats] => Array
(
[0] => Array
(
[amount] => 12166
[perc] => 56.8584380987989
)
[1] => Array
(
[amount] => 1473
[perc] => 6.884142636818245
)
[2] => Array
(
[amount] => 955
[perc] => 4.463242510632331
)
[3] => Array
(
[amount] => 6802
[perc] => 31.789503201383372
)
)
)
PHP is excellent for sorting arrays, but I can't figure out what to use when having this issue.. Take a look of the array above.
I want to sort innner subcats[]
array by the perc
-key from lower to higher.
I want the result to be:
Array opareas
(
[0] => Array
(
[name] = => array('opname1')
[subcats] => Array
(
[0] => Array
(
[amount] => 1
[perc] => 0.011394712853236098 //Lowest percentage value
)
[1] => Array
(
[amount] => 3679
[perc] => 41.921148587055605
)
[2] => Array
(
[amount] => 9883
[perc] => 112.61394712853236 //Highest percentage value
)
)
)
[1] => Array
(
[name] = => array('opname2');
[subcats] => Array
(
[0] => Array
(
[amount] => 955
[perc] => 4.463242510632331 //Lowest percentage value
)
[1] => Array
(
[amount] => 1473
[perc] => 6.884142636818245
)
[2] => Array
(
[amount] => 12166
[perc] => 56.8584380987989
)
[3] => Array
(
[amount] => 6802
[perc] => 31.789503201383372 //Highest percentage value
)
)
)
I've tried with this:
class whateverArray {
private function sort_subcats_perc($a, $b) {
if ($a['subcats']['perc'] == $b['subcats']['perc'] ) {return 0;}
return ( $a['subcats']['perc'] < $b['subcats']['perc'] ) ? -1 : 1;
}
public function showStuff() {
$opareas = array(); //Given above
//Sort subcat array from low to high based on perc-key
uasort( $opareas, array( $this, 'sort_subcats_perc') );
}
);
}
I don't want the actual opareas[0]
and operas[1]
to switch position (is what happens when using the function I've tried) in the array, I only WANT the inner array subcats[] to change it's order based on perc-field/key. Is this possible with uasort
? Or any other builtin of PHP excellent sorting functions?