Foreach within the while in the output of Json

1

I'm looking for a few days ago to do a foreach within a while to print the json data related to that query. My scenario is this:

<?php
require_once('../Connections/db.php');
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$tabelabd = "carros";

$con = @mysqli_connect($hostname_db, $username_db, $password_db, $database_db);

if (!$con) {
 trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM carros WHERE idusuario='1' AND ativo='1' ORDER BY id DESC";
$result = mysqli_query($con, $sql);

while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"'.$tabelabd.'":'.json_encode($var).'}';
?>

Json's output of this is:

[  
   {  
      "id":"1",
      "idusuario":"1",
      "data_cadastro":"2015-09-11",
      "ativo":"S",
      "titulo":"Gol 2009",
      "galeria":"20",
      "destaque":"S"
   },
   {  
      "id":"2",
      "idusuario":"1",
      "data_cadastro":"2015-09-11",
      "ativo":"S",
      "titulo":"Ford Ka 2002",
      "galeria":"21",
      "destaque":"S"
   }
]

// PRECISO QUE A SAIDA SEJA COM A LISTA DE FOTOS(FOREACH) ASSIM:

[  
   {  
      "id":"1",
      "idusuario":"1",
      "data_cadastro":"2015-09-11",
      "ativo":"S",
      "titulo":"Gol 2009",
      "cor":"Prata",
      "galeria":[  
         {  
            "foto_id":1,
            "opcional_nome":"Foto 01"
         },
         {  
            "foto_id":2,
            "opcional_nome":"Foto 03"
         },
         {  
            "foto_id":3,
            "opcional_nome":"Foto 03"
         }
      ],
      "destaque":"S",
   },
   {  
      "id":"2",
      "idusuario":"1",
      "data_cadastro":"2015-09-11",
      "ativo":"S",
      "titulo":"Ford Ka 2002",
      "galeria":[  
         {  
            "foto_id":7,
            "opcional_nome":"Foto 01"
         }
      ],
      "destaque":"S",
   }
]

Could someone instruct me how to do this query? My table is "Gallery" and has the listing of photos and each one is saved with a relationship id (in that case, that id that I can print today in Json).

    
asked by anonymous 11.09.2015 / 20:10

1 answer

3

Within WHILE (), for each car you need to make a new query in the gallery table and include these objects in the car's. An example:

while($obj = mysqli_fetch_object($result)) {
    $sql_galeria = "SELECT * FROM galeria WHERE idcarro='". $obj->id ."'";
    $result_galeria = mysqli_query($con, $sql_galeria);
    while ($galeria = mysqli_fetch_object($result_galeria)) {
        $obj->galeria[] = $galeria;
    }
    $var[] = $obj;
}
echo '{"'.$tabelabd.'":'.json_encode($var).'}';
  • Corrected from your comment.
11.09.2015 / 20:20