2017-05-28 87 views
1

我有一個多值的數組。用PHP計算總數的多個值的百分比

foreach($results as $row) { 
    $count = $row['count']; 
    $type = $row['type']; 
    $array[$type][] = $count; 
} 

當我輸出的數組它看起來像這樣

Type Count 
    AA  4 
    AE  59 
    AF  13 
    BB  44 
    BC  16 
    BD  36 

我現在想用百分比第三列,但我不知道如何實現一個表?

例如AA是5%,AE是39%等。

我該怎麼做?

+0

你需要知道的所有值的總和,然後就'( $計數/ $總和)* 100' – dage5

回答

1

我沒有得到您的建議進行同樣的計算,但這裏是我的方法:

$results=[ 
    ['type'=>'AA','count'=>4], 
    ['type'=>'AE','count'=>59], 
    ['type'=>'AF','count'=>13], 
    ['type'=>'BB','count'=>44], 
    ['type'=>'BC','count'=>16], 
    ['type'=>'BD','count'=>36] 
    ]; 
$total=array_sum(array_column($results,'count')); 
foreach($results as $row) { 
    $array[$row['type']]=[$row['count'],(int)round($row['count']/$total*100)]; 
    // or round($row['count']/$total*100).'%' <-- if you want the % sign 
} 
var_export($array); 

輸出:

array (
    'AA' => 
    array (
    0 => 4, 
    1 => 2, 
), 
    'AE' => 
    array (
    0 => 59, 
    1 => 34, 
), 
    'AF' => 
    array (
    0 => 13, 
    1 => 8, 
), 
    'BB' => 
    array (
    0 => 44, 
    1 => 26, 
), 
    'BC' => 
    array (
    0 => 16, 
    1 => 9, 
), 
    'BD' => 
    array (
    0 => 36, 
    1 => 21, 
), 
)