php - 将数组合并为一组
问题描述
对不起,可能是愚蠢的问题,但真的需要你的帮助。我有数组:
{"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);
谢谢
解决方案
如果您想继续您的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);
推荐阅读
- php - PostgreQL 从多维数组类型的 Json 字段中获取数据
- ruby-on-rails - 在循环中查找匹配项
- netty - ByteToMessageDecoder 网络
- cuda - 是否有将 half2 转换为 float2 的主机功能,反之亦然?
- javascript - 检查用户过去是否已经访问过链接
- powerquery - Power Query,拆分列日期和时间不起作用
- virtualbox - Virtualbox 网络、VM 内部通信、VM 和主机通信、VM 互联网通信
- excel - 删除工作表时将 VBA 执行传递给模块
- javascript - React Native FlatList 的 scrollToEnd() 不起作用
- javascript - 茉莉花元素上的间谍点击事件