Php, calculate percentage on multiple items

后端 未结 5 1376
迷失自我
迷失自我 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:13

    Simple With loop method to do

    $arr = array
    (
    0 => array
        (
            "label" => "Item1",
            "data" => 849,
        ),
    
    1 => array
        (
            "label" => "Item2",
            "data" => 657,
        ),
    
    2 => array
        (
            "label" => "Item3",
            "data" => 571,
        ),
    
    3 => array
        (
            "label" => "Item4",
            "data" => 538,
        ),
    
    4 => array
        (
            "label" => "Item5",
            "data" => 446,
        ),
    
    );
    
    $totalElement = count($arr);
    $data = 0;
    foreach ($arr as $key => $value) {
        $data += $value['data'];
    }
    
    echo ($totalElement/$data)*100;
    

    result

     0.16334531198955
    

提交回复
热议问题