2017-05-28 10 views
1

Ich habe ein Array von mehreren Werten.Berechne den prozentualen Anteil von mehreren Werten mit PHP

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

Wenn ich Ausgang des Array in eine Tabelle sieht es aus wie diese

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

ich jetzt eine dritte Spalte mit Prozentsatz will, aber ich weiß nicht, wie zu implementieren?

z.B. AA ist 5%, AE ist 39% etc.

Wie mache ich das?

+0

Sie benötigen Summe aller Werte kennen und dann nur '($ count/$ sum) * 100' – dage5

Antwort

1

Ich habe nicht die gleichen Berechnungen, die Sie vorschlagen, aber hier ist meine Methode:

$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); 

Ausgang:

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, 
), 
) 
Verwandte Themen