I am very new to php and sql and have been trying to figure out how to turn database results into pretty json format. My main issue is that I cannot group results by data type.
Below is the table, php code and results.
This is how the table looks.
+------+--------------+-------------+-----------+
| 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);
}
}
These are the results, which work, but I want to see if I could group the results by the type. So, if kitten is fluffy, then they should the grouped by that.
{
"kittens_data": [
{
"id": "1",
"type": "fluffy",
"color": "tricolor",
"cuteness": "10",
},
{
"id": "2",
"type": "shorthair",
"color": "brown",
"cuteness": "5",
}
]
}
Something like this the json below. Is it even possible?
{
"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"
}]
}
]
}
Any help, or pointing in the right direction will greatly help.