简体   繁体   中英

How to create a flat JSON Object instead of array of objects in PHP

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);

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"}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM