duanboshi1472 2015-06-26 12:22
浏览 44
已采纳

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

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条回答 默认 最新

  • dongmo3413 2015-06-26 12:31
    关注

    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"}
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料