如何使用 php 中的 foreach 循环中的数据创建 json 数组

how to create a json array with data from a foreach loop in php

我有一些 json 文件如下所示:

{
    "id": "id_11-08-2021",
    "name": "John",
    "date": "11-08-2021",
    "day": "Wednesday",
    "starttime": "08:30",
    "endtime": "10:00",
    "hours": 1.5
}

要读取目录中的所有 json 文件,我使用此代码 (process.php):

$files = glob('data/*.json'); // all json files in dir data
foreach($files as $file) {
    $objs[] = json_decode(file_get_contents($file),1); // all json objects in array             
}
$result = [];
foreach($objs as $key => $val) {
    $result['data'] = array(                                
                        'id' => $val['id'];
                        'date' => $val['date'];
                        'day' => $val['day'];
                        'starttime' => $val['starttime'];
                        'endime' => $val['endtime'];
                        'hours' => $val['hours']                                    
                        );
}
$result['name'] = $_POST['name'];
$result['status'] = 2;
echo json_encode($result); // send back data

我的 jquery ajax 看起来像这样:

$.ajax({
        type: "POST",
        url: "process.php",
        data: {
            name: name          
        },
        dataType: "json",
        success: function(response) {
            if(response.status == 2) { // check status of data
                $('tbody').html(response.data); // handle data from server; output data in tbody
                $('.name').html(response.name); // name from user
            }
        },
});

我没有收到来自 foreach 循环的数据。出了什么问题?

首先,你不断地在循环中覆盖你的结果。您需要在循环中的 data 中创建一个新的数组元素。

$result = [];
foreach ($objs as $key => $val) {
    $result['data'][] = array(                                
        'id' => $val['id'];
        'date' => $val['date'];
        'day' => $val['day'];
        'starttime' => $val['starttime'];
        'endime' => $val['endtime'];
        'hours' => $val['hours']                                    
    );
}
$result['name'] = $_POST['name'];
$result['status'] = 2;

其次,由于您没有更改循环中的任何内容,您可以只使用 $objs 数组并删除循环。该循环在您的示例中没有执行任何操作。

$result['data'] = $objs;