I was trying to create a flat JSON Object from three arrays in PHP. The output of the following code is an object containing array of objects:
{
"Amphibian":[
{"Frogs":"Green"}
],
"Mammal":[
{"Bats":"Black"},
{"Elephants":"Grey"},
{"Rats":"Black"},
{"Turtles":"Green"}
]
}
However, that is not what I want. Is it possible to turn the output to be an object containing flat objects during the loop? This is my desired output :
{
"Amphibian":
{"Frogs":"Green"},
"Mammal":
{"Bats":"Black","Elephants":"Grey","Rats":"Black","Turtles":"Green"}
}
Here's the 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 as $key=>$animal){
if(isset($group[$animal])){
$groupTitle = $group[$animal];
}
$output[$groupTitle][] = array($animal=>$colors[$animal]);
}
print JSON_encode($output);