所以我有一个看起来像这样的数组:
Array ( [Safari] => 13 [Firefox] => 5 )
我如何创建一个如下所示的新数组:
Array ( [Safari] => 72.2% [Firefox] => 27.7% )
使用简洁的 php 函数?
提前致谢。
最佳答案
您可以使用 array_sum()
获取总数,然后迭代返回新值的值。
$total = array_sum($share);
foreach($share as &$hits) {
$hits = round($hits / $total * 100, 1) . '%';
}
CodePad .
如果您有 >= PHP 5.3,使用匿名函数可能会更优雅一些。
$total = array_sum($share);
$share = array_map(function($hits) use ($total) {
return round($hits / $total * 100, 1) . '%';
}, $share);
CodePad .
关于php - 如何将数组键值转换为百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6146645/