从数据库中获取数据后,我的结果如下JSON格式:
"return_data": {
"friend_info": [
{
"desc": "name",
"value": "Ken"
},
{
"desc": "profile_pic",
"value": "http://aaa.caa/1234569/picture?type=large"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想让JSON看起来像:
"return_data": {
"friend_info": [
{
"name": "Ken",
"profile_pic": "http://aaa.caa/1234569/picture?type=large"
}
]
}
Run Code Online (Sandbox Code Playgroud)
但是我完全不知道如何让它像上面的结构一样.有人请让我知道正确的方向,比如我应该使用什么功能等等.谢谢
您需要使用json转换为php数组json_decode()并获取目标值并使用自定义结构插入新对象,然后将新值替换为json数组.最后将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);
Run Code Online (Sandbox Code Playgroud)
在演示中检查结果
请注意,您显示的json无效且应该包含在内 {}