在Laravel PHP框架中如何将两个JSON对象合并为单个JSON对象
Laravel 合并两个JSON对象的实现方案
你可以先将JSON字符串解码为关联数组,合并后再重新编码为JSON即可,两种常用实现方式如下:
方式1:使用数组方法实现
// 定义你的两个原始JSON字符串 $jsonA = '{"device_id":null,"collector_id":2}'; $jsonB = '{"id":1,"name":"hello","email":"w@so2.com","location":null,"latitude":null,"longitude":null}'; // 解码为关联数组,第二个参数传true表示返回数组而非对象 $arrA = json_decode($jsonA, true); $arrB = json_decode($jsonB, true); // 合并数组,后传入的数组键值会覆盖前序的同名字段,无重复字段则直接追加 $mergedArr = array_merge($arrB, $arrA); // 编码为JSON字符串输出 $mergedJson = json_encode($mergedArr);
注:如果两个JSON存在同名键,array_merge会使用后传入数组的取值覆盖前序数组的同键取值
方式2:使用Laravel集合方法实现(更符合Laravel编码规范)
$jsonA = '{"device_id":null,"collector_id":2}'; $jsonB = '{"id":1,"name":"hello","email":"w@so2.com","location":null,"latitude":null,"longitude":null}'; $collectionA = collect(json_decode($jsonA, true)); $collectionB = collect(json_decode($jsonB, true)); // 合并集合并直接转为JSON格式 $mergedJson = $collectionB->merge($collectionA)->toJson();
两种方式最终输出的$mergedJson都和你给出的预期结果完全一致。
内容的提问来源于stack exchange,提问作者AMARASINGHE R.A.A.U.
相关产品推荐
相关产品推荐

