dongmi19720408 2014-12-19 02:18
浏览 91
已采纳

将数组数组转换为json

i want to convert this array as shown below

array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));

into this format:

"3":{"Egypt":{"7":Tanta,"1000":"other"}},"80":{"India":{"0":"All","1":Ahmedabad}}

I am using PHP and not able to figure out how can i do this. I have used json_encode. but the results are not correct.I am using PHP as my language.

thanks in advance

  • 写回答

3条回答 默认 最新

  • dongmang3961 2014-12-19 02:35
    关注

    Before converting into json, you should change the array:

    $array_countries_formated = array();
    
    foreach ($array_countries as $item)
    {
        $array_countries_formated[$item['cntryValue']][$item['cntryLabel']][$item['value']] = $item['label'];
    }
    
    echo $array_countries_formated = json_encode($array_countries_formated, JSON_FORCE_OBJECT);
    

    Result:

    {"3":{"Egypt":{"7":"Tanta","1000":"Other"}},"80":{"India":{"0":"All","1":"Ahmedabad"}}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部