Problem when mounting JSON with database return

0

It all comes down to this image:

asked by anonymous 15.04.2017 / 18:11

2 answers

1

A simple way to fix the problem with the help of MySQL is to use the GROUP_CONCAT() and then use explode() of PHP.

This way it would look like:

SELECT nome, group_concat(data) FROM pessoa GROUP BY nome

This will return all dates in a single row, grouped by name. At the end the result of MySQL will be as follows, for example:

+---------+-----------------------+
| Nome    | Data                  |
+---------+-----------------------+
| Ana     | 2016-01-01,2017-01-01 |
| Bob     | 2000-01-01            |
| Charlie | 2016-12-01,2017-01-03 |
+---------+-----------------------+

In this way all dates will be together, allowing you to use explode(',', $Data) to break the dates, which are separated by commas.

Then it would be enough to use:

while($linha = mysqli_fetch_array($query)){

    $json_array[] = [
        'Nome' => $linha['nome'],
        'Data' => explode(',', $linha['data'])
    ];

}

echo json_encode($json_array);
    
18.04.2017 / 15:46
0

There is a similar question in stackoverflow in English . To achieve the desired effect you can use some ORM (from larvelable frameworks, cakePHP, ... or something standalone like notorm). Using any of these will require a relative learning curve.

The above question link suggests two alternatives:

Query in the first table, cycle through the results with a foreach, create a new array for each row returned. Then do a second query for each row returned. Another foreach to iterate over each row of the second query and create a new array, to put inside the first query.

The second possibility is to do a single query (as you did), and mount the array of fetchAll the hierarchy you want.

    
15.04.2017 / 22:07