PHP生成条形图的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了PHP生成条形图的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:

<?php
  // create an array of values for the chart. These values 
  // could come from anywhere, POST, GET, database etc. 
  $values = array(23,32,35,57,12,3,36,54,32,15,43,24,30);
 
  // now we get the number of values in the array. this will 
  // tell us how many columns to plot 
    $columns  = count($values);
 
  // set the height and width of the graph image
 
    $width = 300; 
    $height = 200;
 
  // Set the amount of space between each column 
    $padding = 5;
 
  // Get the width of 1 column 
    $column_width = $width / $columns ;
 
  // set the graph color variables 
    $im        = imagecreate($width,$height); 
    $gray      = imagecolorallocate ($im,0xcc,0xcc,0xcc); 
    $gray_lite = imagecolorallocate ($im,0xee,0xee,0xee); 
    $gray_dark = imagecolorallocate ($im,0x7f,0x7f,0x7f); 
    $white     = imagecolorallocate ($im,0xff,0xff,0xff);
 
  // set the background color of the graph 
    imagefilledrectangle($im,0,0,$width,$height,$white);
 
 
  // Calculate the maximum value we are going to plot 
  $max_value = max($values);
 
  // loop over the array of columns 
    for($i=0;$i<$columns;$i++) 
        {
    // set the column hieght for each value 
        $column_height = ($height / 100) * (( $values[$i] / $max_value)
 
*100); 
    // now the coords
        $x1 = $i*$column_width; 
        $y1 = $height-$column_height; 
        $x2 = (($i+1)*$column_width)-$padding; 
        $y2 = $height;
 
        // write the columns over the background 
        imagefilledrectangle($im,$x1,$y1,$x2,$y2,$gray);
 
        // This gives the columns a little 3d effect 
        imageline($im,$x1,$y1,$x1,$y2,$gray_lite); 
        imageline($im,$x1,$y2,$x2,$y2,$gray_lite); 
        imageline($im,$x2,$y1,$x2,$y2,$gray_dark); 
        }
 
   // set the correct png headers 
   header ("Content-type: image/png"); 
  // spit the image out the other end 
  imagepng($im); 
?>

运行效果如下图所示:

希望本文所述对大家的PHP程序设计有所帮助。

相关文章

php基于mcrypt的加密解密实例

本文实例讲述了php基于mcrypt实现加密解密的方法。分享给大家供大家参考。具体实现方法如下: PHP中自带了相当多的加密的方法,这里我们来看一下mcrypt扩展的使用方式。也是在工作...

PHP删除目录及目录下所有文件的方法详解

函数代码一:删除目录及目录下的所有文件复制代码 代码如下://循环删除目录和文件函数function delDirAndFile( $dirName ){if ( $handle = o...

PHP Ajax中文乱码问题解决方法

是因为XMLHttp在处理返回的responstText的时候把responstBody按UTF-8编码进行解码的,如果服务器端送出的数据流的确是UTF-8编码,那么中文字就会正确显示,...

使用PHP下载CSS文件中的图片的代码

共享一段使用PHP下载CSS文件中的图片的代码 复制代码 代码如下: <?php //note 设置PHP超时时间 set_time_limit(0); //note 取得样式文件...

探讨php中遍历二维数组的几种方法详解

在PHP应用当中,二维数组的应用算是高频率的了,尤其遇到较为复杂的计算时,基本上都要用到二维或者多维数组的,而在编历多维数组使用的较多的应该是 for 循环遍历和 foreach 遍历两...