Lieven Detilloux Lieven Detilloux - 6 months ago 39
PHP Question

Reverse sorting array inside an object based on an subarray's value in PHP

My object looks like this:

object(stdClass)#1 (1) {
["drives"]=>
array(2) {
[0]=>
array(2) {
["drive"]=>
string(11) "Drive1"
["features"]=>
array(4) {
["statusCode"]=>
int(1)
["UsedValue"]=>
string(4) "222"
["TotalValue"]=>
string(5) "22222"
["smart"]=>
string(1) "0"
}
}
[1]=>
array(2) {
["drive"]=>
string(5) "Drive2"
["features"]=>
array(4) {
["statusCode"]=>
int(0)
["UsedValue"]=>
string(6) "2222"
["TotalValue"]=>
string(7) "222222"
["smart"]=>
string(1) "0"
}
}
}
}


How can I sort the array
drives
based on the value of
statusCode
that's inside the subarray
features
, from the highest number to the lowest?

I need to preserve this structure, I can't put the
statusCode
in the
Drive
array.

Answer

Use uasort(to preserve keys) function for such case:

// $obj is your initial stdClass object
uasort($obj->drives, function($a,$b){
    return $b['features']['statusCode'] - $a['features']['statusCode'];
});
Comments