Sort PHP Array With Two Values

104 Views Asked by At

For example, say I have a PHP array in this format:

[
{"optionname":"Math","optionid":"35741"},
{"optionname":"Robotics","optionid":"80229"},
{"optionname":"fndbwoiaghoe","optionid":"1105065296"},
{"optionname":"iphewajgiewohfoidsahg","optionid":"1385274203"},
{"optionname":"wpeogagpoar","optionid":"1030886790"},   
{"optionname":"genpwaighipwe","optionid":"1193090269"}
]

How can I sort the array by the value of "optionname" alphabetically?

Thanks!

1

There are 1 best solutions below

14
On BEST ANSWER

I am assuming, due to your code example, that you have a JSON-encoded array.

You want to sort not on the value but on a specific property of the value. PHP can't know which specific property you want to take into account. You have to give PHP a way to know which object comes in front of another with your own function. Then you can tell PHP to use that function for the sorting comparison using usort().

$arr = json_decode('
[
    {"optionname":"Math","optionid":"35741"},
    {"optionname":"Robotics","optionid":"80229"},
    {"optionname":"fndbwoiaghoe","optionid":"1105065296"},
    {"optionname":"iphewajgiewohfoidsahg","optionid":"1385274203"},
    {"optionname":"wpeogagpoar","optionid":"1030886790"},   
    {"optionname":"genpwaighipwe","optionid":"1193090269"}
]
');

usort($arr, function ($obj1, $obj2) {
    return strcasecmp($obj1->optionname, $obj2->optionname);
});

$arr = json_encode($arr);

Note that the code above compares the optionname property case insensitive. If you want PHP to take case into account, replace strcasecmp with strcmp.

Edit: If you are using a PHP version older than 5.3, anonymous functions (like the one used as the second parameter to the usort() function above) are not yet supported. The version below should work then.

$arr = json_decode('
[
    {"optionname":"Math","optionid":"35741"},
    {"optionname":"Robotics","optionid":"80229"},
    {"optionname":"fndbwoiaghoe","optionid":"1105065296"},
    {"optionname":"iphewajgiewohfoidsahg","optionid":"1385274203"},
    {"optionname":"wpeogagpoar","optionid":"1030886790"},   
    {"optionname":"genpwaighipwe","optionid":"1193090269"}
]
');

function compareObjects($obj1, $obj2)
{
    return strcasecmp($obj1->optionname, $obj2->optionname);
}
usort($arr, 'compareObjects');

$arr = json_encode($arr);