我收到了Eloquent的回复,我需要完全按照以下步骤设置其格式:
{
name: "James",
data: {
"2017-01-01 00:00:00": 300,
"2017-01-02 00:00:00": 600,
}
},
我得到的当前答复是:
{
name: "James",
date: "2017-01-01 00:00:00",
amount: "300"
},
{
name: "James",
date: "2017-01-02 00:00:00",
amount: "600"
},
我已经绑好了,但是格式不正确:
$chartData = [];
foreach($charts as $chart){
array_push($chartData, [
'name' => $chart->name,
'data' => json_encode([$chart->date. ':' .$chart->amount], true)
]);
}
结果是:
{
name: "James",
data: "{"2017-01-01T00:00:00.000000Z":"300"}"
},
{
name: "James",
data: "{"2017-01-02T00:00:00.000000Z":"600"}"
},
谢谢
答案 0 :(得分:0)
您可以这样做:
$ chartData = [];
foreach($charts as $chart){
array_push($chartData, [
'name' => $chart->name,
'data' => $chart->date. ':' .$chart->amount
]);
}
json_encode($ chartData);
答案 1 :(得分:0)
这必须分两个步骤完成:
function normalizeChartData($charts){
$chartData = [];
//1) grab dates and amounts for each name.
foreach($charts as $chart)
foreach($chart->data as $data){
if(isset($chartData[$chart->name]) && is_array($chartData[$chart->name]))
$chartData[$chart->name][$data->date] = $data->amount;
else
$chartData[$chart->name] = [$data->date => $data->amount];
}
//2) format it to look as you want.
$enhancedChartData = [];
foreach($chartData as $name => $date_amount){
$temp = [
'name' => $name,
'data' => []
];
foreach($date_amount as $da)
$temp['data'][] = $da;
$enhancedChartData[] = $temp;
}
return $enhancedChartData;
}