Fredmat
Fredmat

Reputation: 958

PHP calculate percentage

I've tried many tricks to calculate the percentage of each value in this array, but cannot find a solution. Values are points. Thank you.

<?php

$data = array(
    'item1' => array(
        'label'   => 'Label 1',
        'value'   => 120
    ),
    'item2' => array(
        'label'   => 'Label 2',
        'value'   => 90
    ),
    'item3' => array(
        'label'   => 'Label 3',
        'value'   => 88
    ),
    'item4' => array(
        'label'   => 'Label 4',
        'value'   => 19
    )
);

?>

The last thing I've tried is the following:

<?php

$percentages = array();
$total_items = count( $data );

foreach ( $data as $item ) {

    foreach ( $item as $k => $v ) {

        if ( $k == 'value' ) {

            $percentages[] = ( $v / $total_items ) * 100;

        }

    }

}

?>

Hope this edit will let you know more about what I'm trying to achieve.

Upvotes: -1

Views: 6933

Answers (1)

Steve
Steve

Reputation: 20469

You will need to do two passes over the data, one to calculate the total, then the next to calculate percentages:

$total = 0;
$percentages=[];

foreach ( $data as $item )
    $total += $item['value'];

foreach ( $data as $key=> $item )
    $percentages[$key]= $item['value'] / ($total /100);

var_dump($percentages);

example: http://codepad.viper-7.com/qAQ5YW

Upvotes: 2

Related Questions