我试图从 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"} }
关于php - 如何在 PHP 中创建平面 JSON 对象而不是对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31073087/