我试图将多维php数组转换为JSON格式。 问题是JSON添加数组中每个值的“数字键”。使用php转换JSON格式的嵌套数组显示数字索引而不是数组名称
对于构建JSON,首先我做一个查询,然后,为了追加另一个具有每个地点营业时间的数组,我对每个结果都做了另一个查询。
这是我得到的JSON:
{
"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"
}
}
}
.....
]
}
这是我想要的JSON:
{
"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"
}
}
}
.....
]
}
这是我用追加一个阵列到另一个代码。请注意,$ result是mysql查询的结果。
/* 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);
}
}
而我使用的数组转换为JSON格式的代码:
header('Content-type: application/json');
echo json_encode(array('sucursales'=>$sucursales));
你要使用同一个键对多个对象..? –