php - 如何将数组键值转换为百分比

标签 php arrays

所以我有一个看起来像这样的数组:

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/

相关文章:

javascript - PHP 搜索文件中不匹配的行

php - 使用 php 构建和重建 CSS 数据 uris

php - 如果旧的 img 上传具有不同的扩展名,我如何用新的 img 上传覆盖它们

c - 如何遍历数组以将它们复制到另一个 uint32_t 类型的数组中?

php - 将多个值与数组匹配

php - 如果不是非主行的副本,则sql查询仅更新

php - Yii2:如何根据前几页的总和在页脚中添加总和?

c - 已分配动态数组,但不能使用它

c - 如何检查数组中的数字是否相等?

c# - C# 中的 JSON 到 ListView