subhra subhra - 1 year ago 72
JSON Question

How to sort json array value as per key value using PHP

I need one help. I need to sort my json array as per key value and resize it using php. I am explaining my code below.

$skillArr=array(array("type"=>1,"name"=>"aaa"),array("type"=>2,"name"=>"bbb"),array("type"=>1,"name"=>"ccc"),array("type"=>3,"name"=>"ddd"),array("type"=>2,"name"=>"eee"),array("type"=>1,"name"=>"fff"));
echo json_encode($skillArr);
?>


The above array is giving me the following output.

[{"type":1,"name":"aaa"},{"type":2,"name":"bbb"},{"type":1,"name":"ccc"},{"type":3,"name":"ddd"},{"type":2,"name":"eee"},{"type":1,"name":"fff"}]


Here I need to sort this array as per
type value
. My expected output is given below.

[{"type1":[{"type":1,"name":"aaa"},{"type":1,"name":"ccc"},{"type":1,"name":"ff"}],"type2":[{"type":2,"name":"bbb"},{"type":2,"name":"eee"}],"type3":[{"type":3,"name":"ddd"}]}]


The output array should be like above after sorting. Please help me.

Answer Source

You can use usort to sort your array.

$skillArr=array(array("type"=>1,"name"=>"aaa"),array("type"=>2,"name"=>"bbb"),array("type"=>1,"name"=>"ccc"),array("type"=>3,"name"=>"ddd"),array("type"=>2,"name"=>"eee"),array("type"=>1,"name"=>"fff"));
usort($skillArr, function($a, $b){return $a['type'] - $b['type'];});
echo json_encode($skillArr);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download