Doubt JSON PHP

Asked

Viewed 59 times

0

I’m trying to display on the screen a structure JSON which will be built by Mysql, but I would like to separate the results into groups according to the name of the fields 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);
?>

1 answer

1


You can do it like 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);
  • Hi Rayann. Nice to meet you. First, thank you for your help. Dude, it was great, but there’s a way to keep it all separate, skipping lines both in the scores and results, which even I didn’t show in the question above and which doesn’t interfere with the reading of JSON ?

  • I built the array to reproduce the example you quoted. For you to read the whole json ident and line breaking you need to install an extension in your browser, for example Jsonview.

  • Okay, thanks buddy

  • @abduzeedo I edited the response with a constant for json_encode(), this should print the json the way you expect it to.

  • Bacana, just a doubt, how do I have a general puzzle and inside my fields, example: array( here inside the json fields )? I edited my example of how json has to be.

  • I updated the answer.

  • 1

    Rayann Nayran. Thank you so much for your help, I have already signaled your response.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.