gpt4 book ai didi

php - Laravel 创建一个 JSON 数组

转载 作者:可可西里 更新时间:2023-11-01 00:30:07 26 4
gpt4 key购买 nike

尝试为 Morris.js 圆环图创建一个 JSON 数组,但想不出任何方法来获得正确的格式。有什么建议吗?

我的 Controller :

    $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"} ...]'

最佳答案

您的代码正在为 $data2 数组创建两个子数组,一个 label 和一个 value。然后,将数据一遍又一遍地推送到这两个数组。

相反,您想要创建一个新数组并将其推送到 $data2 数组,如下所示:

$data2 = [];
foreach ($labels as $label)
{
$data2[] = [
'label' => $label,
'value' => $budget->sum($label)
];
}

关于php - Laravel 创建一个 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37220529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com