代码之家  ›  专栏  ›  技术社区  ›  André Castro

JSON-规范内部的de格式

  •  -1
  • André Castro  · 技术社区  · 6 年前

    我已在中转换了一个数组 JSON . 但是转换将数组放入 JSON文件

    我的转换是:

    {"title":"acastro","description":"teste acastro 4","category_id":29,"region_id":3,"city_id":3158063,"district_id":"1","contact":{"person":"Classe Car"},"0":{"make":"Mercedes-Benz"},"1":{"model":"GLC 220"},"2":{"engine_code":"Classe A"}
    

    你能从钥匙开始吗 "0":{"make":"Mercedes-Benz"} ,JSON的内部发生了变化,我无法将其提交给api。

    我需要我的JSON对象完全像它的: "title":"acastro","description":"teste acastro 4","category_id":29,"make":"Mercedes-Benz","model":"GLC220",.. .

    我试过了 json_encode JSON_FORCE_OBJECT

    有什么解决办法吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Senior PHP Developer    6 年前

    您可以尝试以下代码,但尚未测试:

    $json   =   '{"title":"acastro","description":"teste acastro 4","category_id":29,"region_id":3,"city_id":3158063,"district_id":"1","contact":{"person":"Classe Car"},"0":{"make":"Mercedes-Benz"},"1":{"model":"GLC 220"},"2":{"engine_code":"Classe A"}}';
    
        $newArr     =   array();
    function recursiveArrayShiftToRoot($array, &$newArr=array()){
        global $newArr ;
        foreach($array as $index=>$eachMixVal){
            if(is_array($eachMixVal)){
                recursiveArrayShiftToRoot($eachMixVal);
            }else{
                $newArr[$index] =   $eachMixVal;
            }
        }
    }
    recursiveArrayShiftToRoot(json_decode($json, true), $newArr);
    

    enter image description here