首页 > 解决方案 > 如何使用 php 从 foreach 循环中检索 json_encode 数据

问题描述

在一个目录中,我有很多 json 文件,如下所示:

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

通过 ajax,我尝试从所有这些文件中接收数据:

$.ajax({
    type: "POST",
    url: "process.php",
    data: {
        show_hours: 1,
        name: name          
    },
    processData: false,
    dataType: "json",
    success: function(response) {
        if(response.status == 2) {
            $('tbody').html(response.data); // output in table body
        }
    },
    error: function() {
        alert('Something went wrong!');
    }
});

process.php看起来像这样:

$result = [];
if( isset($_POST['show_hours']) ) {
    $files = glob('data/'.$year.'/'.$month.'/'.$name.'/*.json'); // all json files
    foreach($files as $file) {
        $objs[] = json_decode(file_get_contents($file),1); // all json objects in array             
    } 
    foreach($objs as $key => $val) {
    
        $result['data'] = array(
                            'tr' => '<tr>';
                            'id' => '<td class="d-none">'.$val['id'].'</td>';
                            'date' => '<td>'.$val['date'].'</td>';
                            'day' => '<td>'.$val['day'].'</td>';
                            'starttime' => '<td>'.$val['starttime'].'</td>';
                            'endime' => '<td>'.$val['endtime'].'</td>';
                            'hours' => '<td class="calc-hours">'.$val['hours'].'</td>';
                            'tr' => '</tr>';
                            );

    }
    $result['status'] = 2; // status 2 for show data by name
    echo json_encode($result);

但我收到了警报Something went wrong!

我做错了什么?

标签: phpjsonajaxforeach

解决方案


推荐阅读