user2059600
user2059600

Reputation:

Laravel create a JSON array

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

Upvotes: 9

Views: 42646

Answers (1)

Joel Hinz
Joel Hinz

Reputation: 25414

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)
    ];
}

Upvotes: 20

Related Questions