【问题标题】:Calculate percentage of multiple values of total with PHP用PHP计算多个总值的百分比
【发布时间】:2017-10-29 04:33:52
【问题描述】:

我有一个包含多个值的数组。

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% 等等。

我该怎么做?

【问题讨论】:

  • 你需要知道所有值的总和,然后($count/$sum)*100

标签: php arrays rounding percentage


【解决方案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,
  ),
)

【讨论】:

    猜你喜欢
    • 2018-04-19
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 2021-02-20
    相关资源
    最近更新 更多