Reputation: 165
I'm trying to convert a multidimensional php array into JSON format. The problem is that JSON add the "numeric key" of each value of the array.
For constructing the JSON, first I make a query, and then, for append another array which have the business hours of each place, I do another query for each result.
This is the JSON that I get:
{
"sucursales": [
{
"sucursal": {
"id_sucursal": "104",
"id_user": "2",
"nombre_sucursal": "wena ql 2",
"region": "0",
"0": {
"dia": "1",
"hora_inicio": "600",
"hora_fin": "600"
},
"1": {
"dia": "2",
"hora_inicio": "600",
"hora_fin": "600"
},
"2": {
"dia": "3",
"hora_inicio": "600",
"hora_fin": "600"
},
"3": {
"dia": "4",
"hora_inicio": "600",
"hora_fin": "600"
}
}
}
.....
]
}
This is the JSON that I want:
{
"sucursales": [
{
"sucursal": {
"id_sucursal": "104",
"id_user": "2",
"nombre_sucursal": "wena ql 2",
"region": "0",
"horario": {
"dia": "1",
"hora_inicio": "600",
"hora_fin": "600"
},
"horario": {
"dia": "2",
"hora_inicio": "600",
"hora_fin": "600"
},
"horario": {
"dia": "3",
"hora_inicio": "600",
"hora_fin": "600"
},
"horario": {
"dia": "4",
"hora_inicio": "600",
"hora_fin": "600"
}
}
}
.....
]
}
This is the Code that I use for appending one array to another one. Note that $result is the result of a mysql query.
/* create one master array of the records */
$sucursales = array();
if(mysql_num_rows($result)) {
while($sucursal = mysql_fetch_assoc($result)) {
$query_horarios = "SELECT dia,hora_inicio,hora_fin FROM horario_funcionamiento WHERE id_sucursal=".$sucursal['id_sucursal'].";";
$resultado_horarios = mysql_query($query_horarios,$link) or die('Error en la consulta SQL'); //.$query);
while($horario = mysql_fetch_assoc($resultado_horarios)){
$sucursal[]= $horario;
}
$sucursales[] = array('sucursal'=>$sucursal);
}
}
And the code that I use for converting the array to JSON format:
header('Content-type: application/json');
echo json_encode(array('sucursales'=>$sucursales));
Upvotes: 0
Views: 177
Reputation: 100195
i dont think thats possible, instead you could do:
....
while($horario = mysql_fetch_assoc($resultado_horarios)){
$sucursal['horario'][] = $horario;
}
...
Upvotes: 1