9

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

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

1 Answer 1

20

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

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

$data2 = [];
foreach ($labels as $label)
{
    $data2[] = [
        'label' => $label,
        'value' => $budget->sum($label)
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.