I'm thinking how to group my array by objects with the same value.
I have this result from MySQL query:
| Id | Name | Date | Value | |----|-------------|--------------|---------| | 1 | Jeff | 2014-12-01 | 5 | | 1 | Jeff | 2015-12-01 | 8 | | 2 | David | 2014-12-01 | 7 | | 2 | David | 2015-12-01 | 6 |
If I use echo json_encode():
$json = array();
while($row = mysqli_fetch_assoc($result)) {
$bus = [
'id' => $row["id"],
'name' => $row["name"],
'date' => $row["date"],
'value' => $row["value"]
];
array_push($json, $bus);
}
echo json_encode($json);
the result is:
[
{
"Id": "1",
"Name": "Jeff",
"Date": "2014-12-01",
"Value": "5"
},
{
"Id": "1",
"Name": "Jeff",
"Date": "2015-12-01",
"Value": "8"
},
{
"Id": "2",
"Name": "David",
"Date": "2014-12-01",
"Value": "7"
},
{
"Id": "2",
"Name": "David",
"Date": "2015-12-01",
"Value": "6"
}
]
but, Is it possible to get the json array like this with php ?
[
{
"Id": "1",
"Name": "Jeff",
"Values":[
{
"2014-12-01": "5",
"2015-12-01": "8"
}
]
},
{
"Id": "2",
"Name": "David",
"Values":[
{
"2014-12-01": "7",
"2015-12-01": "6"
}
]
}
]
group by Name?