尝试为Morris.js圆环图创建一个JSON数组,但无法想出任何获得正确格式的方法。有什么提示吗?
我的控制器:
$user = User::find((Auth::user()->id));
$budget = $user->budget()->get();
$labels = ['rent', 'heating', 'utilities', 'internet_tv', 'phone', 'food', 'sweets', 'alcohol_cigs', 'insurance' , 'loans', 'finance_other', 'cosmetics'
, 'medicine', 'clothes_shoes', 'accessories', 'electronics', 'school', 'entertainment', 'food_out', 'holidays', 'books', 'pets', 'gifts', 'car', 'other'];
$data2 = [];
foreach ($labels as $label)
{
$data2['label'][] = $label;
$data2['value'][] = $budget->sum($label);
}
$data2 = json_encode($data2);
我得到的是什么:
'{"label":["rent","heating","utilities","internet_tv" ...],"value":[435,30,0,0 ...]}'
我想得到:
'[{"label":"rent","value":"435"},{"label":"heating","value":"30"},{"label":"utilities","value":"0"},{"label":"internet_tv","value":"0"} ...]'
答案 0 :(得分:5)
您的代码正在为$data2
数组创建两个子数组,一个label
和一个value
。然后,数据被反复推送到这两个数组。
相反,您想要创建一个新数组并将其推送到$data2
数组,如下所示:
$data2 = [];
foreach ($labels as $label)
{
$data2[] = [
'label' => $label,
'value' => $budget->sum($label)
];
}