我尝试使用以下代码创建二维数组,但它将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;
$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
}]
}
答案 0 :(得分:2)
您必须在不使用自己定义的索引的情况下对其进行索引。
如果必须使用fila
作为索引,那么您必须了解编码的JSON将是一个对象。您可以将json_decode重新编码为数组,例如:json_decode($json, 1);
否则,在对数组进行编码之前,您可以调用:$arr = array_values($arr);
,这会导致在调用json_encode
后数组被编码为JSON数组。
答案 1 :(得分:2)
如果你确定你的List<Rook> pieces = new ArrayList<>();
List<Piece> cloned = pieces.stream()
.map(p -> (Piece) p.clone())
.collect(Collectors.toList());
}
字段将包含&#34;索引&#34; (我的意思是从0开始的连续整数),然后你可以使用fila
将它们转换为整数。
intval
否则,最好只对记录进行分组并创建一组数组。
if ($result) {
while ($row = mysqli_fetch_object($result)) {
$arr[intval($row->fila)][] = (array) $row;
}
}