PHP calculate percentage -


i've tried many tricks calculate percentage of each value in array, cannot find solution. values 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 following:

<?php  $percentages = array(); $total_items = count( $data );  foreach ( $data $item ) {      foreach ( $item $k => $v ) {          if ( $k == 'value' ) {              $percentages[] = ( $v / $total_items ) * 100;          }      }  }  ?> 

hope edit let know more i'm trying achieve.

you need 2 passes on data, 1 calculate total, next calculate percentages:

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

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


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -