Chartjs - 循环数据集并指定颜色

时间:2018-05-02 12:47:58

标签: php arrays loops chart.js linechart

我想根据数据的值在行图中指定pointBackgroundColor。 我有这个数组(例子):

Array ( [0] => 7 [1] => 2 [2] => 5 [3] => 6 [4] => 5 [5] => 6 [6] => 7 [7] => 5 [8] => 6 [9] => 4 [10] => 1 [11] => 2 [12] => 7 [13] => 1 [14] => 2 [15] => 1 [16] => 2 )

我将intColors初始化为颜色数组 我已经在$ arrDataSets中加入了构建图表的参数 我现在需要知道如何根据条件定义颜色
例如,如果值> 2然后pointBackgroundColor =绿色?

$intColors = array("#82f827", "#ff4040", "#31698A", "#6666FF","#ff7F50","#fe6b60","#6c1ba1","#97bdd6");
foreach($datasetR1 as $value){

            }

            $arrDatasets = array(
                array('label' => "event_name",
                      'fill' => false,
                      'showLine' => false,
                      'pointBackgroundColor' => $intColors,
                      'data' => $datasetR1
                      ));
            $arrReturn = (array('labels' => $labels, 
                    'datasets' => $arrDatasets));
            $mydata = json_encode(($arrReturn));

1 个答案:

答案 0 :(得分:0)

foreach($datasetR1 as $value){
                if($value == 1){
                    array_push($intColors, "#82f827");
                }
                elseif($value == 2){
                    array_push($intColors, "#ff4040");
                }
                elseif($value == 3){
                    array_push($intColors, "#31698A");
                }
                elseif($value == 4){
                    array_push($intColors, "#6666FF");
                }
                elseif($value == 5){
                    array_push($intColors, "#ff7F50");
                }
                elseif($value == 6){
                    array_push($intColors, "#fe6b60");
                }
                elseif($value == 7){
                    array_push($intColors, "#6c1ba1");
                }
                elseif($value == 8){
                    array_push($intColors, "#97bdd6");
                }
            }