Php 如何创建JSON编码的2D数组?
我试图用下面的代码创建一个二维数组,但它将JSON编码为一个对象。我该如何解决这个问题Php 如何创建JSON编码的2D数组?,php,Php,我试图用下面的代码创建一个二维数组,但它将JSON编码为一个对象。我该如何解决这个问题 $result = $bd->query("select * from contenidos where idfolleto=$idf order by fila"); $arr = array(); if ($result) { while ($row = mysqli_fetch_object($result)) { $filaAct = $row->fila;
$result = $bd->query("select * from contenidos where idfolleto=$idf order by fila");
$arr = array();
if ($result) {
while ($row = mysqli_fetch_object($result)) {
$filaAct = $row->fila;
$arr[$filaAct][] = (array) $row;
}
}
echo json_encode($arr);
输出为:
{
"1": [{
"id": "6",
"idfolleto": "1",
"fila": "1",
"orden": "1",
"tipo": "carrousel",
"titulo": "",
"subtitulo": null,
"color1": null,
"color2": null,
"color_fondo": null
}],
"2": [{
"id": "7",
"idfolleto": "1",
"fila": "2",
"orden": "1",
"tipo": "texto-imagenes",
"titulo": "Texto 1",
"subtitulo": null,
"color1": null,
"color2": null,
"color_fondo": null
}, {
"id": "8",
"idfolleto": "1",
"fila": "2",
"orden": "2",
"tipo": "texto-imagenes",
"titulo": "Texto 2",
"subtitulo": null,
"color1": null,
"color2": null,
"color_fondo": null
}],
"3": [{
"id": "9",
"idfolleto": "1",
"fila": "3",
"orden": "3",
"tipo": "texto-imagenes",
"titulo": "Texto 3",
"subtitulo": null,
"color1": null,
"color2": null,
"color_fondo": null
}]
}
您必须在不使用自己定义的索引的情况下对其进行索引 如果您必须使用
fila
作为索引进行维护,那么您必须了解编码的JSON将是一个对象。您可以将其json_解码回一个数组,但类似于:json_解码($json,1)代码>
否则,在编码数组之前,可以调用:$arr=array\u值($arr)
这将导致数组被编码为JSON数组,一旦调用JSON\u encode
您就必须在不使用自己定义的索引的情况下对其进行索引
如果您必须使用fila
作为索引进行维护,那么您必须了解编码的JSON将是一个对象。您可以将其json_解码回一个数组,但类似于:json_解码($json,1)代码>
否则,在编码数组之前,可以调用:$arr=array\u值($arr)
一旦调用JSON\u encode
将导致数组被编码为JSON数组,如果您确定fila
字段将包含“索引”(我指从0开始的连续整数),则可以使用intval
将其转换为整数
if ($result) {
while ($row = mysqli_fetch_object($result)) {
$arr[intval($row->fila)][] = (array) $row;
}
}
否则,最好只对记录进行分组并创建一个组数组
if ($result) {
$groups = array();
while ($row = mysqli_fetch_object($result)) {
$groups[$row->fila][] = (array) $row;
}
$arr = array_values($groups);
}
如果您确定fila
字段将包含“索引”(我是指从0开始的连续整数),则可以使用intval
将它们转换为整数
if ($result) {
while ($row = mysqli_fetch_object($result)) {
$arr[intval($row->fila)][] = (array) $row;
}
}
否则,最好只对记录进行分组并创建一个组数组
if ($result) {
$groups = array();
while ($row = mysqli_fetch_object($result)) {
$groups[$row->fila][] = (array) $row;
}
$arr = array_values($groups);
}
如果您想返回数组,请尝试json\u decode($arr,true)
。您将获得一个数组而不是对象数组。但是json_decode()要求参数1为string如果您想要返回数组,请尝试json_decode($arr,true)
。您将得到一个数组而不是对象数组。但是json_decode()希望参数1为string。我想我将回顾一下我的实现,避免使用“fila”作为索引。谢谢我想我将回顾我的实现,避免将“fila”作为索引。谢谢我想我将回顾我的实现,避免将“fila”作为索引。谢谢我想我将回顾我的实现,避免将“fila”作为索引。谢谢