How to create a flat JSON Object instead of array of objects in PHP -
i trying create flat json object 3 arrays in php. output of following code object containing array of objects:
{ "amphibian":[ {"frogs":"green"} ], "mammal":[ {"bats":"black"}, {"elephants":"grey"}, {"rats":"black"}, {"turtles":"green"} ] }
however, not want. possible turn output object containing flat objects during loop? desired output :
{ "amphibian": {"frogs":"green"}, "mammal": {"bats":"black","elephants":"grey","rats":"black","turtles":"green"} }
here's code:
$colors = array("frogs"=>"green","bats"=>"black","elephants"=>"grey","rats"=>"black","turtles"=>"green"); $allanimals = array("frogs","bats","elephants","rats","turtles"); $group = array("frogs"=>"amphibian","bats"=>"mammal"); $output = array(); foreach($allanimals $key=>$animal){ if(isset($group[$animal])){ $grouptitle = $group[$animal]; } $output[$grouptitle][] = array($animal=>$colors[$animal]); } print json_encode($output);
modify $output[$grouptitle][$animal] = $colors[$animal];
$colors = array("frogs"=>"green","bats"=>"black","elephants"=>"grey","rats"=>"black","turtles"=>"green"); $allanimals = array("frogs","bats","elephants","rats","turtles"); $group = array("frogs"=>"amphibian","bats"=>"mammal"); $output = array(); foreach($allanimals $key=>$animal){ if(isset($group[$animal])){ $grouptitle = $group[$animal]; } $output[$grouptitle][$animal] = $colors[$animal]; //here } print json_encode($output);
output:
{ "amphibian":{"frogs":"green"}, "mammal":{"bats":"black","elephants":"grey","rats":"black","turtles":"green"} }
Comments
Post a Comment