Php 将Laravel5.2中的JSON文件合并到主JSON的特定部分中
我正在尝试将Laravel5.2中的JSON文件合并到主JSON的特定部分 案例: 我有一个主config.jsonPhp 将Laravel5.2中的JSON文件合并到主JSON的特定部分中,php,json,laravel,laravel-5,laravel-5.2,Php,Json,Laravel,Laravel 5,Laravel 5.2,我正在尝试将Laravel5.2中的JSON文件合并到主JSON的特定部分 案例: 我有一个主config.json { "layout": "normal", "modules": [ "module1", "module2", "module3" ] } 我有许多模块json文件,如下所示(这个问题的最小值): 我想实现的目标:在“模块”所在的部分(模块1、模块2等),我想依次加载其他json文件并保存文件。它们中的每一个都是一个对象,因此理想情况下它看起来像: {
{
"layout": "normal",
"modules": [
"module1", "module2", "module3"
]
}
我有许多模块json文件,如下所示(这个问题的最小值):
我想实现的目标:在“模块”所在的部分(模块1、模块2等),我想依次加载其他json文件并保存文件。它们中的每一个都是一个对象,因此理想情况下它看起来像:
{
"layout": "normal",
"modules": [
{
"name": "module1",
"description": "lorem ipsum"
},
{
"name": "module2",
"description": "lorem ipsum"
}
}
所有文件都存储在resources/assets/json中,每个json都有modulename作为文件名,如下所示:
/json
_module1.json
_module2.json
....
问题:如何在Laravel 5.2中实现这一点?PHP不提供直接处理JSON数据的可能性。为了在PHP中向JSON添加数据,您需要首先将其解码为关联数组,更新数据,然后再次编码为JSON 下面应该可以做到这一点:
// decode original JSON
$decodedData = json_decode($json, true);
// read and decode data for all listed modules into an array
$moduleData = [];
foreach ($decodedData['modules'] as $module) {
$moduleData[] = json_decode(file_get_contents("json/_$module.json"), true);
}
// add module data to the main array
$decodedData['modules'] = $moduleData;
// encode back into JSON
$json = json_encode($decodedData);
// decode original JSON
$decodedData = json_decode($json, true);
// read and decode data for all listed modules into an array
$moduleData = [];
foreach ($decodedData['modules'] as $module) {
$moduleData[] = json_decode(file_get_contents("json/_$module.json"), true);
}
// add module data to the main array
$decodedData['modules'] = $moduleData;
// encode back into JSON
$json = json_encode($decodedData);