2

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);
1
  • There is no difference between the first JSON object and the second JSON object. What am I missing here? Commented Jun 26, 2015 at 12:45

1 Answer 1

5

Modify it to $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 as $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"}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.