Laravel 创建一个 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37220529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:48:15  来源:igfitidea点击:

Laravel create a JSON array

phpjsonlaravelloops

提问by Deividas Pranaitis

Trying to create a JSON array for Morris.js donut chart, but cant think of any way to get correct format. Any tips?

试图为 Morris.js 甜甜圈图创建一个 JSON 数组,但想不出任何方法来获得正确的格式。有小费吗?

My 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);

What I am getting:

我得到了什么:

'{"label":["rent","heating","utilities","internet_tv" ...],"value":[435,30,0,0 ...]}'

I want to get:

我想得到:

'[{"label":"rent","value":"435"},{"label":"heating","value":"30"},{"label":"utilities","value":"0"},{"label":"internet_tv","value":"0"} ...]'

回答by Joel Hinz

Your code is creating two subarrays to the $data2array, one labeland one value. Then, data is pushed to these two arrays over and over again.

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

Instead, you want to create a new array and push that one onto the $data2array, like this:

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

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