Php, calculate percentage on multiple items

后端 未结 5 1375
迷失自我
迷失自我 2020-12-20 05:31

I have 5 items in total, and I would like to calculate percentage based on [data] filed. The result will be used for pie chart.

Array
(
    [0] => Array
          


        
5条回答
  •  鱼传尺愫
    2020-12-20 06:20

    If you want your code to be flexible:

    $array= [
          0 => [
            'label' => 'Item1',
            'data' => 849,
            ],
          1 => [
            'label' => 'Item1',
            'data' => 849,
            ],
          2 => [
            'label' => 'Item1',
            'data' => 849,
            ],
          3 => [
            'label' => 'Item1',
            'data' => 849,
          ],
          4 => [
            'label' => 'Item1',
            'data' => 849,
            ],
          5 => [
            'label' => 'Item1',
            'data' => 849,
            ]
    ];
       foreach($array as $key => $val){
         $sum +=$val['data'];
       }
      echo "output  =  ".(count($val['data'])/$sum)*100;
    ?>
    

提交回复
热议问题