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!
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()
.Note that the code above compares the optionname property case insensitive. If you want PHP to take case into account, replace
strcasecmp
withstrcmp
.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.