Doubt JSON PHP

0

I'm trying to display a JSON structure that will be built by MySQL , but I would like to separate the results into groups according to the field names I set in select and would like something like:

minha_array
    carro
        carro 1
        carro 2
        carro 3
        carro 4
    imagem
        imagem 1
        imagem 2
        imagem 3
        imagem 4

My code:

<?php

//open connection to mysql db
$connection = mysqli_connect("localhost","root","","mybd") or die("Error " . mysqli_error($connection));

//fetch table rows from mysql db
$sql = "select carro, imagem from carros";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
    $emparray[] = $row;
}
echo json_encode($emparray);

//close the db connection
mysqli_close($connection);
?>
    
asked by anonymous 09.05.2017 / 21:15

1 answer

1

You can do this:

while($row = mysqli_fetch_assoc($result)) {
    $emparray['minha_array']['carro'][] = $row['carro'];
    $emparray['minha_array']['imagem'][] = $row['imagem'];
}

echo json_encode($emparray, JSON_PRETTY_PRINT);
    
09.05.2017 / 22:08