The output from the mysql db query is like this (example):
type count amount
---- ----- ------
A 1 100
B 2 200
C 3 300
and so on... that is saved in a php variable called $data
From this result, I want to loop through the result and create a php array that will output json like this:
{
"types": [
{
"type": "A",
"count": 1,
"amount": 100
}
{
"type": "B",
"count": 2,
"amount": 200
}
{
"type": "C",
"count": 3,
"amount": 300
}
]
}
What I have done so far ... I am able to loop through them like this:
foreach($data as $k=>$v) {
echo $v->type;
echo $v->count;
echo $v->amount;
}
How do I create a php array with this? I know how to convert to JSON but I need help in writing the loop that will create the array in that format.
CodePudding user response:
Without knowing how you get data into the $data
variable, you can construct a new array this way:
$array = ['types' => []];
foreach ($data as $k => $v) {
$array['types'][] = [
'type' => $v->type,
'count' => $v->count,
'amount' => $v->amount
];
}
echo json_encode($array, JSON_PRETTY_PRINT);
CodePudding user response:
From the code you've posted, you already have an array of objects. From that you can simply create the parent object and assign the data to it:
// json_encode will create JSON objects for PHP arrays with string keys.
$parent = ['types'=>$data];
echo json_encode($parent, JSON_PRETTY_PRINT);