-1

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.

function drawCSSGraph($data, $total, $settings='height=20 width=300 color=#c0c0c0'){
  //Emulate the symfony style of using settings
  if(is_array($settings)){
    $width = (isset($settings['width']))?$settings['width']:300;
    $height = (isset($settings['height']))?$settings['height']:20;
    $color = (isset($settings['color']))?$settings['color']:'#c0c0c0';
  } else {
    $settings = explode(' ', $settings);
    foreach($settings as $setting){
      $tmp = explode('=', $setting);
      $$tmp[0] = $tmp[1];
      if(!isset($width)) $width = 300;
      if(!isset($height)) $height = 20;
      if(!isset($color)) $color = '#c0c0c0';
    }
  }
  
  if(count($data) > 1){
    $HTMLoutput = '';
    foreach($data as $label=>$var){
      $labelv = preg_replace('/\[var\]/', $var, $label);
      $HTMLoutput .= drawCSSGraph(array($labelv=>$var), $total, $settings);
    }
    return $HTMLoutput;
  } else {
    $variable = $data[key($data)];
    $label = preg_replace('/\[var\]/', $variable, key($data));
    return 
     '<div><span>'.$label.'</span>
         <div style="width:'.$width.'px;height:'.$height.'px;border:1px solid black;padding:1px;">
            <div class=\'bargraph\' style=\''.
                (($width > $height)?'width':'height').':'.
                (($variable/$total)*($width > $height?$width:$height)).'px;background-color:'.$color.';\'></div>
         </div>
    </div>'."\n";
  }
}
1
Contributor
1
Reply
2
Views
9 Years
Discussion Span
Last Post by ShawnCplus
0

Small addition, in the argument list, if you change $total to $total=null Then right before if(count... you add the following

if($total == 0 || $total == null){
    foreach($data as $key=>$value){
      $total += $value;
    }
  }

You no longer have to pass a total since it will just do it for you. (small oversight on my part not to add it in the first place)

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.