Skip to content
Advertisement

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

i have some json files which look like this:

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

To read all the json files in a dir i use this code (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

My jquery ajax looks like this:

$.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
            }
        },
});

I do not receive the data from the foreach loop. What is going wrong?

Advertisement

Answer

First of all, you’re overwriting your result in the loop constantly. You need to create a new array element within data in the loop.

$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;

Secondly, since you’re not changing anything in your loop, you could just use your $objs array and remove the loop. The loop doesn’t do anything in your example.

$result['data'] = $objs;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement