How to create a JSON file from PHP

0

I need to build a JSON file from PHP with a specific sequence, but I do not know how to build it.

The sequence is as follows:

[{"jornada":"A","colegios":["Salle","Belemitas"]},
{"jornada":"B","colegios":["Nazaret","Comfama","jega"]}]

the database is as follows:

id  |  colegio  |  jornada  |
-----------------------------
1   | Salle     | A         |
-----------------------------
2   | Nazaret   | B         |
-----------------------------
3   | Comfama   | B         |
-----------------------------
4   | Belemitas | A         |
-----------------------------
5   | Jega      | B         |
-----------------------------
6   | Rosario   | Unica     |
-----------------------------

My attempt at PHP

    $con = mysqli_connect($server, $user, $password, $database);
    if (mysqli_connect_errno()) {
        echo "APP: " . mysqli_connect_error();
    }

    $query = mysqli_query($con, "SELECT * FROM ge_colegios ORDER BY jornada DESC;  ");


    $json = '[';


    while ($row = mysqli_fetch_array($query)){
        $char ='"';
        $json .= 
        '{

            COMO CONSTRUYO LE SECUENCIA AQUI?

        },';
    }


    // buat menghilangkan koma diakhir array
    $json = substr($json,0,strlen($json)-1);

    $json .= ']';

    echo $json; 
    mysqli_close($con);

?>

Thanks

    
asked by pidiendoenUSA Saag 20.12.2018 в 04:59
source

2 answers

0

To generate a json I use this code:

while($row = mysqli_fetch_array($result))      {         $json[]=array('valor1'=> $row['valor1'], 'valor2'=> $row['valor2']); }

$json_string = json_encode($json); echo $json_string;

p / d: the json variable created it inside the while

    
answered by 20.12.2018 в 07:59
0

What I do is create an array and then go through the data. Finally I code them with the json_encode. It would be like this:

$query = mysqli_query($con, "SELECT * FROM ge_colegios ORDER BY jornada DESC;  ");

$datos = array();

foreach ($query as $row) {

    $datos[] = $row;

}

echo json_encode($datos);

I hope it helps you. Good luck!

    
answered by 20.12.2018 в 09:00