L
L
lev892021-02-27 09:03:35
PHP
lev89, 2021-02-27 09:03:35

How to convert data from table to json file?

I need to get some data from a table and then convert the query to a .json file. For some reason, only the last line of the table is written to the file. Where did I go wrong?

<?php

$query = \R::getAll("SELECT YEAR(updated_at) AS year,MONTHNAME(updated_at) AS month,COUNT(*) AS cnt FROM tickets GROUP BY YEAR(updated_at), MONTHNAME(updated_at)"); // использую ORM Redbeanphp
$data = array();
foreach ($query as $item) {
    $data = [
            'Year' => $item['year'],
            'Month' => $item['month'],
            'Count' => $item['cnt']
    ];
}

$json_data = json_encode($data);
file_put_contents('your_json_file.json', $json_data);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-02-27
@lev89

How it is written is how it is recorded.

foreach ($query as $item) {
    $data[] = [
            'Year' => $item['year'],
            'Month' => $item['month'],
            'Count' => $item['cnt']
    ];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question