代码之家  ›  专栏  ›  技术社区  ›  ken

如何使用php改变JSON的结构[[关闭]

  •  -2
  • ken  · 技术社区  · 7 年前

    从数据库中提取数据后,我的结果以JSON格式显示如下:

    "return_data": {
        "friend_info": [
            {
                "desc": "name",
                "value": "Ken"
            },
            {
                "desc": "profile_pic",
                "value": "http://aaa.caa/1234569/picture?type=large"
            }
        ]
    }
    

    我想让JSON看起来像:

    "return_data": {
        "friend_info": [
            {
                "name": "Ken",
                "profile_pic": "http://aaa.caa/1234569/picture?type=large"
            }
         ]
    }
    

    1 回复  |  直到 7 年前
        1
  •  6
  •   Mohammad DefenestrationDay    7 年前

    您需要使用 json_decode() 获取目标值并插入到具有自定义结构的新对象中,然后将新值替换到json数组中。最后,使用 json_encode()

    $json = json_decode($jsonStr, true);
    $obj = new stdClass;
    foreach ($json["return_data"]["friend_info"] as $item)
        $obj->{$item["desc"]} = $item["value"];
    
    $json["return_data"]["friend_info"] = $obj;
    $jsonStr = json_encode($json);
    

    demo

    请注意,您显示的json无效,应该包装到 {}