繁体   English   中英

如何在PHP中创建平面JSON对象而不是对象数组

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

我试图从PHP中的三个数组创建一个平面JSON对象。 以下代码的输出是一个包含对象数组的对象:

{
 "Amphibian":[
     {"Frogs":"Green"}
  ],
 "Mammal":[
    {"Bats":"Black"},
    {"Elephants":"Grey"},
    {"Rats":"Black"},
    {"Turtles":"Green"}
  ]
}

但是,那不是我想要的。 在循环期间是否可以将输出变为包含平面对象的对象? 这是我想要的输出:

{
  "Amphibian":
    {"Frogs":"Green"},
  "Mammal":  
    {"Bats":"Black","Elephants":"Grey","Rats":"Black","Turtles":"Green"}
}

这是代码:

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

修改它为$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);

输出:

{
"Amphibian":{"Frogs":"Green"},
"Mammal":{"Bats":"Black","Elephants":"Grey","Rats":"Black","Turtles":"Green"}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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