Donut
Donut

Reputation: 167

dynamically fill a json variable

I am trying to dynamically fill my chartjs with data from a database. The data is Volume specific (Letter and usage in percent).

Due to the flexibility of the database structure, i decided to put all volume informations in one single cell, which divides each volume with a whitespace and the letter and percentage with a comma.

Now i need to put this data dynamically inside a json variable so i can push it to my chart. At the moment it looks like this:

var jsonData = {
    "L": [{"y": 100}, {"y": 50}, {"y": 40}],
    "C": [{"y": 61}, {"y": 39}, {"y": 59}],
    "": [{"y": 33}, {"y": 97}, {"y": 67}]
}

But those values and volume letters are hardcoded. So i need to split up my php string, which includes the volumes, and somehow pass it for every entry to the json variable.

I need to select each letter once, and every value which belongs to the correspondending letter.

Also i should mention, that the json variable needs to be dynamically extendable because it is possible that there are more than 3 volumes per cell.

Upvotes: 0

Views: 199

Answers (1)

Yassine CHABLI
Yassine CHABLI

Reputation: 3734

Can you try this :

<?php

$data = array('L,100 C,61 ,31', 'L,50 C,39 ,97', ' L,40 C,59 ,67');
$result = array();
foreach($data as $key => $element){
    $parts = explode(" ",$element);
    foreach($parts as $part){
        $underParts = explode(',', $part);
        if(isset($underParts[0]) && isset($underParts[1]) ){
        $result[$underParts[0]][]=array('y'=>$underParts[1]);
        }


    }
}


var_dump(json_encode($result));

The result :

string(118) "{"L":[{"y":"100"},{"y":"50"},{"y":"40"}],"C":[{"y":"61"},{"y":"39"},{"y":"59"}],"":[{"y":"31"},{"y":"97"},{"y":"67"}]}"

Upvotes: 1

Related Questions