我想解析、编辑和合并到一个对象的多个 JSON 文件


multiple JSON files that I would like to parse, edit, and merge into one object,

大家好,大家好

我需要从文件夹中解码多个 .json 文件

我有多个 JSON 文件,我想解析、编辑并合并到一个对象中,最终将重新编码并输出为单个 JSON。

她我的一个.json文件解码的代码

<?php 
    if ( file_exists( BASE . '/contents/cache/recent-file.json' ) ) {
        $recent_file = json_decode( file_get_contents( BASE . '/contents/cache/recent-file.json' ), true );
        if ( $recent_file ) {
?>
    <div class="items-list">
            <?php 
                foreach( array_reverse($recent_file) as $key => $apps ) {
                    get_template( 'templates/app-item', $apps );                    

            ?>
        </div>      
<?php } } ?>  

您需要:

  1. 获取所有 JSON 文件的列表
  2. 获取每个文件的内容
  3. 将这些文件的内容添加到 PHP 数组中
  4. 输出为新的 JSON 对象

我的方法是:

//Get all the JSON files
$files = glob("/path/to/folder/*.json");
//Create an empty new array
$newDataArray = [];
//Get the contents of each file
foreach($files as $file){
    $thisData = file_get_contents($file);
    //Decode the json
    $thisDataArray = json_decode($thisData);
    //Add $thisData to the new array
    $newDataArray[] = $thisDataArray;
}
//Encode the array to JSON
$newDataJSON = json_encode($newDataArray);

现在,您可以使用$newDataJSON对象执行所需的操作,例如将其保存到新的.json文件中:

file_put_contents("/path/to/file.json",$newDataJSON);