Sort PHP Array With Two Values -


this question has answer here:

for example, have php array in 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 sort array value of "optionname" alphabetically?

thanks!

i assuming, due code example, have json-encoded array.

you want sort not on value on specific property of value. php can't know specific property want take account. have give php way know object comes in front of own function. can tell php use function 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 code above compares optionname property case insensitive. if want php take case account, replace strcasecmp strcmp.

edit: if using php version older 5.3, anonymous functions (like 1 used second parameter usort() function above) not yet supported. 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); 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -