【发布时间】:2021-10-25 09:28:58
【问题描述】:
我有一些看起来像这样的 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 循环的数据。出了什么问题?
【问题讨论】:
-
首先,你在每次循环迭代中覆盖
$result['data'],应该是$result['data'] = ...
标签: php arrays json ajax foreach