【问题标题】:Laravel create a JSON arrayLaravel 创建一个 JSON 数组
【发布时间】:2016-09-10 06:31:46
【问题描述】:

尝试为 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"} ...]'

【问题讨论】:

    标签: php json laravel loops


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢!!它节省了我的时间
    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2021-10-25
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多