将Laravel 5.2中的JSON文件合并到主JSON的特定部分


Merge JSON files in Laravel 5.2 in a specific part of the main JSON

我正在尝试将Laravel 5.2中的JSON文件合并到主JSON的特定部分中。

案例:我有一个主要配置.json

{
  "layout": "normal",
  "modules": [
    "module1", "module2", "module3"
  ]
}

我有很多模块json文件,看起来像这样(这个问题的最小值):

{
  "name": "module1",
  "description": "lorem ipsum"
}

我想实现的是:在"modules"所在的部分(module1、module2等)中,我想一个接一个地加载我的其他json文件并保存该文件。它们中的每一个都是一个对象,所以理想情况下看起来像:

{
  "layout": "normal", 
  "modules": [
    {
      "name": "module1",
      "description": "lorem ipsum"
    },
    {
      "name": "module2",
      "description": "lorem ipsum"
    }
}

所有文件都存储在resssources/assets/json中,每个json都有一个模块名作为文件名,如下所示:

/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);