很抱歉可能会提出愚蠢的问题,但确实需要您的帮助。我有数组:
{"code":200,"message":"OK","0":{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"},"1":{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"}}
并且需要实现以下目标:
{"code":200,"message":"OK","records":[{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"},{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"}]}
请让我知道如何使用PHP ...它曾经是我与array_merge($message, $records);
合并的两个数组
谢谢
答案 0 :(得分:1)
如果您想继续进行json
响应,则可以像这样创建一个新数组,但是此示例仅适用于您在问题中提到的json
:
<?php
$array = json_decode('{"code":200,"message":"OK","0":{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"},"1":{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"}}
',true);
$newArray = array(); // initialize new array
foreach ($array as $key => $value) {
if(is_array($value)) { // if having array
$newArray['records'][] = $value;
}
else{
$newArray[$key] = $value;
}
}
echo json_encode($newArray);
?>
结果:
{"code":200,"message":"OK","records":[{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"},{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"}]} Second, if you are mergin two array `array_merge($message, $records);`
第二个解决方案(推荐),如果您要合并两个数组并要添加新索引records
,则还可以通过添加records
索引来修改:
$newArray = $message;
$newArray['records'] = $records;
echo json_encode($newArray);
答案 1 :(得分:1)
如果您需要短代码(一个字符串,两个带有$ result声明)
$json = '{"code":200,"message":"OK","0":{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"},"1":{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"}}';
$result = [];
foreach(json_decode($json,true) as $k=>$v) if(is_array($v)){$result["records"][]=$v;} else {$result[$k]=$v;};
请确保使用您的json更改$ json
结果(漂亮打印):
{
"code": 200,
"message": "OK",
"records": [
{
"title": "Green peppercorn and lemongrass coconut broth",
"media": "\/posts\/images\/84709.jpg"
},
{
"title": "Green peppercorn and lemongrass coconut broth",
"media": "\/posts\/images\/84709.jpg"
}
]
}