开发者

How to convert array key values into percentages

开发者 https://www.devze.com 2023-03-08 13:08 出处:网络
So i\'ve got an array that looks something like of: Array ( [Safari] => 13 [Firefox] => 5 ) How do i a make a new array that looks like :

So i've got an array that looks something like of:

Array ( [Safari] => 13 [Firefox] => 5 )

How do i a make a new array that looks like :

Array ( [Safari] => 72.2% [Firefox] => 27.7% )

using a neat php function开发者_StackOverflow?

thanks in advance.


You can use array_sum() to get the total, then iterate over the values returning the new value.

$total = array_sum($share);

foreach($share as &$hits) {
   $hits = round($hits / $total * 100, 1) . '%';
}

CodePad.

If you have >= PHP 5.3 it can be a tad more elegant with an anonymous function.

$total = array_sum($share);

$share = array_map(function($hits) use ($total) {
   return round($hits / $total * 100, 1) . '%';
}, $share);

CodePad.


    $array=array ( 'Safari' => 13 ,'Firefox' => 5 );
    $tot=array_sum($array);

    foreach($array as $key=>$value){
       $result[$key]=number_format(($value/$total)*100,1).'%';
    }

    print_r($result); //Array ( [Safari] => 72.2% [Firefox] => 27.7% )


Try this:

$array = Array ( 'Safari' => 13, 'Firefox' => 5 );
$total = array_sum($array); # total sum of all elements
$onePercent = $total / 100; # we want to know what value represents 1 percent
array_walk($array, create_function('&$v', '$v /= '.$onePercent.'; $v .= " %";')); # we walk through the array changing numbers to percents
var_export($array);

If you want to have your result in second array leaving $array not touched, you can use array_map instead of array_walk

You also might want to use sprintf to set precision of float values that represent percent, because my code would output:

array (
  'Safari' => '72.2222222222 %',
  'Firefox' => '27.7777777778 %',
)

It's not hard to figure out how to do it?


For PHP 5.3, you can do it like this:

$browsers = array('Safari' => 13, 'Firefox' => 5);

$browsers_proportioned = proportionalize($browsers);

function proportionalize ($arr) {
    $total = array_sum($arr);
    $names = array_map(
            function($number) use ($total) { return number_format($number / $total * 100, 1) .'%'; },
            $arr
    );
    return $names;
}


I personnally like when numbers add up to exactly 100 (not almost 100 like 99.99). So with the solution below, the last item uses the rest instead of being calculated like other items:

public static function getPercentagesByKeyValue(array $arr)
{
    $ret = [];
    $nbItems = count($arr);
    $i = 1;
    $sum = array_sum($arr);
    foreach ($arr as $key => $number) {
        $percent = round($number / $sum * 100, 2);
        if ($i === $nbItems) {
            $percent = 100 - (array_sum($ret));
        }
        $ret[$key] = $percent;
        $i++;
    }
    return $ret;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消