我对php和sql非常陌生,一直在尝试如何将数据库结果转换成漂亮的json格式。我的主要问题是不能按数据类型对结果进行分组。
下面是表格、php代码和结果。
这是桌子的样子。
+------+--------------+-------------+-----------+
| id | type | color | cuteness |
+------+--------------+-------------+-----------+
| 1 | fluffy | tricolor | 10 |
| 2 | shorthair | brown | 5 |
| 3 | angry | white | 9 |
| 4 | fluffy | black | 8 |
| 5 | lazy | white | 10 |
| 6 | fighter | white | 6 |
| 7 | fluffy | black | 8 |
| 8 | shorthair | tricolor | 9 |
| 9 | fluffy | transparent | 7 |
| 10 | shorthair | neon | 10 |
+------+--------------+-------------+-----------+
PHP:
$query = "SELECT * from 'kittens' order by date DESC";
$sendoff = execute($query, 1);
if (num_of_rows($sendoff) > 0) {
//number of rows
$conta = num_of_rows($sendoff);
// kittens array
$kittens_arr=array();
$kittens_arr["kittens_data"]=array();
//displaynumberofkittens
$kittens_arr["count"]= $conta;
while ($kittensori = fetch_array($sendoff)){
//used for future separations
$kitten = $kittensori['category'];
extract($kittensori);
$kittenslist=array(
"type" => $kitten_type,
"name" => $kitte_nname,
"color" => $kitten_color,
"cuteness" => $cuteness,
);
array_push($kittens_arr["kittens_data"], $kittenslist);
}
}
这些是有效的结果,但我想看看是否可以按类型对结果进行分组。所以,如果小猫是毛茸茸的,那么它们应该按这个分组。
{
"kittens_data": [
{
"id": "1",
"type": "fluffy",
"color": "tricolor",
"cuteness": "10",
},
{
"id": "2",
"type": "shorthair",
"color": "brown",
"cuteness": "5",
}
]
}
下面是json。有可能吗?
{
"kittens_data": [
{
"type": "fluffy",
"box": [{
"id": "1",
"color": "tricolor",
"cuteness": "10"
},
{
"id": "7",
"color": "black",
"cuteness": "8"
}]
},
{
"type": "shorthair",
"box": [{
"id": "2",
"color": "brown",
"cuteness": "5"
},
{
"id": "8",
"color": "tricolor",
"cuteness": "9"
}]
}
]
}
任何帮助,或指向正确的方向都会大有帮助。