DaniWeb IT Discussion Community

Code Snippets (http://www.daniweb.com/code/)
-   php (http://www.daniweb.com/code/php.html)
-   -   CSS Bar Graph function (http://www.daniweb.com/code/snippet861.html)

ShawnCplus php syntax
May 8th, 2008
This is a recursive function I made to draw purely CSS bar graphs. You pass it an array of data and the total amount, example:
$someData = array('Oranges'=>4, 'Apples'=>10);
$total = 14;
echo drawCSSGraph($someData, $total);
Also, you can pass it options in the form of an array or as space separated couples, exa:
//perfectly fine
echo drawCSSGraph($data, $total, 'height=20 width=300 color=#c0c0c0');
//works just as well
$options = array('height'=>20, 'width'=>300, 'color'=>'#c0c0c0');
echo drawCSSGraph($data, $total, $options);
Also, you can put [var] in the label which will be parsed out when the graph is drawn
$data = array('Data1: [var]'=>20, 'Data2: [var]'=>19);
echo drawCSSGraph($data, 39);
==>
    Data1: 20
    [graph here]
    Data2: 19
    [graph here]
It will detect whether you're making a vertical or horizontal bar graph and adjust accordingly. If you want it vertical just make the height greater than the width.

  1. function drawCSSGraph($data, $total, $settings='height=20 width=300 color=#c0c0c0'){
  2. //Emulate the symfony style of using settings
  3. if(is_array($settings)){
  4. $width = (isset($settings['width']))?$settings['width']:300;
  5. $height = (isset($settings['height']))?$settings['height']:20;
  6. $color = (isset($settings['color']))?$settings['color']:'#c0c0c0';
  7. } else {
  8. $settings = explode(' ', $settings);
  9. foreach($settings as $setting){
  10. $tmp = explode('=', $setting);
  11. $$tmp[0] = $tmp[1];
  12. if(!isset($width)) $width = 300;
  13. if(!isset($height)) $height = 20;
  14. if(!isset($color)) $color = '#c0c0c0';
  15. }
  16. }
  17.  
  18. if(count($data) > 1){
  19. $HTMLoutput = '';
  20. foreach($data as $label=>$var){
  21. $labelv = preg_replace('/\[var\]/', $var, $label);
  22. $HTMLoutput .= drawCSSGraph(array($labelv=>$var), $total, $settings);
  23. }
  24. return $HTMLoutput;
  25. } else {
  26. $variable = $data[key($data)];
  27. $label = preg_replace('/\[var\]/', $variable, key($data));
  28. return
  29. '<div><span>'.$label.'</span>
  30. <div style="width:'.$width.'px;height:'.$height.'px;border:1px solid black;padding:1px;">
  31. <div class=\'bargraph\' style=\''.
  32. (($width > $height)?'width':'height').':'.
  33. (($variable/$total)*($width > $height?$width:$height)).'px;background-color:'.$color.';\'></div>
  34. </div>
  35. </div>'."\n";
  36. }
  37. }