首页 > 解决方案 > 将数组合并为一组

问题描述

对不起,可能是愚蠢的问题,但真的需要你的帮助。我有数组:

{"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);

谢谢

标签: phparrays

解决方案


如果您想继续您的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);

推荐阅读