[英]dynamically fill a json variable
I am trying to dynamically fill my chartjs with data from a database. 我试图用来自数据库的数据动态填充我的chartjs。 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. 现在,我需要将这些数据动态地放入json变量中,以便可以将其推送到图表中。 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. 因此,我需要拆分我的php字符串(包括卷),并以某种方式将其传递给json变量的每个条目。
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. 我还要提到的是,json变量需要动态扩展,因为每个单元有可能超过3个卷。
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"}]}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.