php 防google 分页效果代码

 更新时间:2016年11月25日 16:29  点击:2078

function getPageRange($currentPage, $totalPages, $displaySize = 10) {
    if ($totalPages <= 0 || $displaySize <= 0) {
        return array();
    } elseif ($displaySize > $totalPages) {
        $startPage = 1;
        $endPage = $totalPages;
    } else {
        if ($currentPage % $displaySize === 0) {
            $startPage = $currentPage - $displaySize + 1;
        } else {
            while (($currentPage % $displaySize)) {
                --$currentPage;
            }
            $startPage = $currentPage + 1;
        }
        if ($startPage <= 0) {
            $startPage = 1;
        }
        $endPage = $startPage + $displaySize - 1;
        if ($endPage > $totalPages) {
            $endPage = $totalPages;
            $startPage = $endPage - $displaySize + 1;
        }
    }
    return range($startPage, $endPage);
}函数getPageRange接受三个参数,当前页$currentPage,总页数$totalPages,和翻页区间长度$displaySize,默认是10。根据这三个参数,函数getPageRange会生成一个适当的包含了$currentPage的翻页区间。首先,我们需要排除非法的参数值,对于总页数或区间长度小于零的情况,须加以检查。

然后,我们考察静态划分的思路。如前所述,给定翻页区间长度后,便可用总页数除以长度,得到区间个数。与此同时,我们可分析得知并不是所有区间都含有相同的页数,在极端情况下,还会出现总页数小于给定的翻页区间长度,那么划分或切割的结果将永远只有一个区间。幸运的是,这不会给我们的核心算法带来什么干扰,但我们仍须重视代码的健壮性。所以,我们先考虑极端情况,在运用算法解决核心问题之前,先迅速捕捉只有一页的区间。

接下来,我们便可以看看区间的固有属性了。每个动态切割的区间,都有一个起始页和一个尾页;由于区间彼此存在先后顺序,所以在经过静态划分后,我们始终会得到第一个(首)区间和最后一个(尾)区间,若首尾区间重合,则说明总页数小于给定的翻页区间长度。无论如何,算法需要解决的关键问题是如何找到区间的起始页和尾页,一旦确定这两个元素,便可以使用PHP内置的range函数生成区间内的全部页码。

算法利用当前页$currentPage和翻页区间长度$displaySize做比较,来判断当前页在区间内所处的位置,进而推导出区间起始页和尾页与当前页的偏移量。为了做到完美无缺,我们还要考虑边界溢出的问题,这也非常简单,只需判断起始页和尾页是否介于1和总页数之间即可。

至此,对于代码的分析已经完成。我们来看一下算法的时间效率,通俗地说,算法中的基本操作是求模,算法的执行时间取决于$currentPage与$displaySize的差值,差值越大,则求模次数越多、执行时间越长,呈线性结构。而实际的执行结果则是在瞬间完成的。

下面,我们来结合上面的Google搜索结果页,利用getPageRange函数生成一个翻页区间,输入所需参数:
print_r(implode(',', getPageRange(18, 27, 20)));得到的结果是:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20大家会发现这和Google搜索结果页显示的完全不一样。对,因为Google的翻页区间把当前页强制设置在中间位置上了!嗯,不要灰心,我们仍可以利用getPageRange函数得到与之相匹配的结果,只需把问题再分解一下:
print_r(implode(',', array_merge(getPageRange(17, 17, 10), getPageRange(27, 27, 10))));得到的结果是:
8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27

php实现多线程
服务器发送多个请求要实现多进程要方便很多。只能使用在cli模式。可以用在特殊场合,如邮件发送任务等。
资源的共享访问使用了文件锁,并不是很可靠,主要是为了能够在Windwos下使用,如果确实有必要可以考虑自己改用相应的信号灯机制(这个扩展只能用于xUNIX)。

实例
[php]
define('DIR_PHP_EXEC', 'php');
define('DIR_MAIN_EXEC', __FILE__);
define('DIR_TMP', '/tmp');
require_once('my_process.php');

class pp extends my_process_base {
    public function run($param = null) {
        for ($i = 0; $i < 4; $i++) {
            echo "111 $paramn";
            sleep(1);
        }
    }
}

init_my_process();
$obj = $GLOBALS['gal_obj_process_m'];
if ($obj->is_main()) {
    $obj->run_task('pp', 'a');
    $obj->run_task('pp', 'b');
    $obj->run_task('pp', 'c');
    $obj->run_task('pp', 'd');
    //$obj->run_task('pp', 'b');
    $obj->set_max_run(10);
    $obj->run();
}

[/php]

进程管理类
[php]
/**
* @copyright 2007 movivi
* @author  徐智  <xzfred@gmail.com>
*
* $Id: getPage.php 11 2007-09-21 02:15:01Z fred $
*/
if (!defined('DIR_PHP_EXEC')) define('DIR_PHP_EXEC', 'php');
//if (!defined('DIR_MAIN_EXEC')) define('DIR_MAIN_EXEC', '');
if (!defined('DIR_TMP')) define('DIR_TMP', '');
/*****************************************************************************/
/* 初始化 */
define('CMD_MAIN_PROCESS_KEY', 'main_process_key');
define('CMD_CHILD_PROCESS_NAME', 'child_process_name');
define('CMD_CHILD_PROCESS_PARAM', 'child_process_param');

function init_my_process() {
    $GLOBALS['gal_obj_cmd'] = new my_cmd_argv();
    $key = $GLOBALS['gal_obj_cmd']->get_value(CMD_MAIN_PROCESS_KEY);
    $key = $key === false ? '' : $key;
    $GLOBALS['gal_obj_process_m'] = new my_process_m($key);
    if (!$GLOBALS['gal_obj_process_m']->is_main()) $GLOBALS['gal_obj_process_m']->run() ;
}

/**
* php多进程类
*
* 你需要从这个对象继承,然后实现你自己的run处理
*/
abstract class my_process_base {
    public function __construct($auto_run=true, $name='') {
    }

    public function __destruct() {
        echo "@endn";
    }

    abstract public function run($param = null);
}


class my_cmd_argv {
    private $cmd_argv = array();
    public function __construct() {
        $argv = $_SERVER['argv'];
        for ($i = 1; $i < count($argv); $i++) {
            $cmd = explode('=', $argv[$i]);
            $this->cmd_argv[$cmd[0]] = isset($cmd[1]) ? $cmd[1] : '';
        }
    }

    public function get_key($key) {
        return isset($this->cmd_argv[$key]);
    }

    public function get_value($key) {
        return isset($this->cmd_argv[$key]) ? $this->cmd_argv[$key] : false;
    }
}

/**
* php多进程管理类
* 可以在PHP中实现多进程处理,只限在控制台方式使用
* 当前的信号实现机制采用文件方式
*
*/
class my_process_m {
    /**
     * @var array $task_list
     * 进程列表
     */
    private $task_list = array();
    private $lock_list = array();
    private $lock = null;
    private $is_main = false;
    private $max_run = 3600000;

    private function release_lock($key = null) {
        $lock = &$this->lock_list;
        if (!is_null($key)) {
            $key = md5($this->build_lock_id($key));
            if (isset($lock[$key])) {
                if (is_resource($lock[$key][0])) fclose($lock[$key][0]);
                unlink($lock[$key][1]);
                unset($lock[$key]);
            }
            return true;
        }

        foreach ($lock as $k => $h) {
            if (is_resource($h)) fclose($h);
            unset($lock[$k]);
        }
        return true;
    }

    private function release_task($key = null) {
        $task = &$this->task_list;
        if (!is_null($key) && isset($task[$key])) {
            if (is_resource($task[$key])) pclose($task[$key]);
            unset($task[$key]);
        } else {
            foreach ($task as $k => $h) {
                if (is_resource($h)) pclose($h);
                unset($task[$k]);
            }
        }
        return true;
    }
           
    private function build_lock_id($key) {
        return DIR_TMP . DIRECTORY_SEPARATOR . $key . '_sem.lock';
    }

    protected function run_child_process() {
        $class = $GLOBALS['gal_obj_cmd']->get_value(CMD_CHILD_PROCESS_NAME);
        $param = $GLOBALS['gal_obj_cmd']->get_value(CMD_CHILD_PROCESS_PARAM);
        $param = $param == '' ? null : unserialize(base64_decode(trim($param)));
        $obj = new $class();
        $obj->run($param);
        $this->task_list[] = $obj;
    }

    public function __construct($lock='') {
        if ($lock === '') {
            $this->is_main = true;
            $key = md5(uniqid()) . '_main.my_process';
            $lock = array($key, $this->get($key));
        } else {
            $this->is_main = false;
            $lock = array($lock, 0);
        }
        $this->lock = $lock;
    }

    public function __destruct() {
        $this->release_lock();
        $this->release_task();
    }

    /**
     * 停止所有进程
     *
     */
    public function stop_all() {
    }

    /**
     * 是否是主进程
     *
     */
    public function is_main() {
        return $this->is_main;
    }

    /**
     * 是不是已经存在一个活动信号
     *
     * @param   string      $key
     * @return  bool       
     */
    public function exist($key) {
        return file_exists($this->build_lock_id($key));
    }

    /**
     * 获取一个信号
     *
     * @param   string      $key    
     * @param   int         $max_acquire    最大请求阻塞数量
     * @return mix 如果成功返回一个信号ID
     *
     */
    public function get($key, $max_acquire=5) {
        $fn = $this->build_lock_id($key);
        if (isset($this->lock_list[md5($fn)])) return false;
        $id = fopen($fn, 'a+');
        if ($id) $this->lock_list[md5($fn)] = array($id, $fn);
        return $id;
    }

    /**
     * 释放一个信号
     *
     * @param   string      $key    
     * @return  bool        如果成功返回一个信号true
     *
     */
    public function remove($key) {
        return $this->release_lock($key);
    }

    /**
     * 获取一个信号
     *
     * @param string    $id         信号ID
     * @param bool      $block      是否阻塞
     */
    public function acquire($id, $block=false) {
        if ($block) {
            return flock($id, LOCK_EX);
        } else {
            return flock($id, LOCK_EX + LOCK_NB);
        }
    }

    /**
     * 释放一个信号
     *
     */
    public function release($id) {
        flock($id, LOCK_UN);
    }
    public function run_task($process_name, $param=null) {
        $this->task_list[] = popen(DIR_PHP_EXEC . ' -f ' . DIR_MAIN_EXEC . ' -- '
            . CMD_CHILD_PROCESS_NAME . '=' . $process_name . ' '
            . CMD_CHILD_PROCESS_PARAM . '="' . base64_encode(serialize($param)) . '" '
            . CMD_MAIN_PROCESS_KEY . '="' . $this->lock[0] . '" ',
            'r');
    }

    public function run($auto_run = true) {
        if ($this->is_main) {
            $ps = &$this->task_list;
            $max_run = &$this->max_run;
            $id = 0;
            do {
                //echo "process----------------------------------------: n";
                $c = 0;
                foreach ($ps as $k => $h) {
                    $c++;
                    $msg = fread($h, 8000);
                    if (substr($msg, -5, 4) === '@end') {
                        echo "end process:[$k][$id] echo n{$msg} n";
                        $this->release_task($k);
                    } else {
                        echo "process:[$k][$id] echo n{$msg} n";
                    }
                }
                sleep(1);
            } while ($auto_run && $id++ < $max_run && $c > 0);
        } else {
            $this->run_child_process();
        }
    }

    public function set_max_run($max=1000) {
        $this->max_run = $max;
    }
}

class show_page {

    /**
     * 页面输出结果
     *
     * @var string
     */
 var $output;

    /**
     * 使用该类的文件,默认为 PHP_SELF
     *
     * @var string
     */
 var $file;

    /**
     * 页数传递变量,默认为 'p'
     *
     * @var string
     */
 var $pvar = "p";

    /**
     * 页面大小
     *
     * @var integer
     */
 var $psize;

    /**
     * 当前页面
     *
     * @var ingeger
     */
 var $curr;

    /**
     * 要传递的变量数组
     *
     * @var array
     */
 var $varstr;

    /**
     * 总页数
     *
     * @var integer
     */
    var $tpage;

    /**
     * 分页设置
     *
     * @access public
     * @param int $pagesize 页面大小
     * @param int $total    总记录数
     * @param int $current  当前页数,默认会自动读取
     * @return void
     */
    function set($pagesize=20,$total,$current=false) {
  global $HTTP_SERVER_VARS,$HTTP_GET_VARS;

  $this->tpage = ceil($total/$pagesize);
  if (!$current) {$current = $HTTP_GET_VARS[$this->pvar];}
  if ($current>$this->tpage) {$current = $this->tpage;}
  if ($current<1) {$current = 1;}

  $this->curr  = $current;
  $this->psize = $pagesize;

  if (!$this->file) {$this->file = $HTTP_SERVER_VARS['PHP_SELF'];}

  if ($this->tpage > 1) {
           
   if ($current>10) {
    $this->output.='<a href='.$this->file.'?'.$this->pvar.'='.($current-10).($this->varstr).' title="前十页">&lt;&lt;&lt;</a>&nbsp;';
   }
            if ($current>1) {
    $this->output.='<a href='.$this->file.'?'.$this->pvar.'='.($current-1).($this->varstr).' title="前一页">&lt;&lt;</a>&nbsp;';
   }

            $start = floor($current/10)*10;
            $end = $start+9;

            if ($start<1)   {$start=1;}
            if ($end>$this->tpage) {$end=$this->tpage;}

            for ($i=$start; $i<=$end; $i++) {
                if ($current==$i) {
                    $this->output.='<font color="red">'.$i.'</font>&nbsp;';    //输出当前页数
                } else {
                    $this->output.='<a href="'.$this->file.'?'.$this->pvar.'='.$i.$this->varstr.'">['.$i.']</a>&nbsp;';    //输出页数
                }
            }

            if ($current<$this->tpage) {
    $this->output.='<a href='.$this->file.'?'.$this->pvar.'='.($current+1).($this->varstr).' title="下一页">&gt;&gt;</a>&nbsp;';
   }
            if ($this->tpage>10 && ($this->tpage-$current)>=10 ) {
    $this->output.='<a href='.$this->file.'?'.$this->pvar.'='.($current+10).($this->varstr).' title="下十页">&gt;&gt;&gt;</a>';
   }
  }
 }

    /**
     * 要传递的变量设置
     *
     * @access public
     * @param array $data   要传递的变量,用数组来表示,参见上面的例子
     * @return void
     */ 
 function setvar($data) {
  foreach ($data as $k=>$v) {
   $this->varstr.='&amp;'.$k.'='.urlencode($v);
  }
 }

    /**
     * 分页结果输出
     *
     * @access public
     * @param bool $return 为真时返回一个字符串,否则直接输出,默认直接输出
     * @return string
     */
 function output($return = false) {
  if ($return) {
   return $this->output;
  } else {
   echo $this->output;
  }
 }

    /**
     * 生成Limit语句
     *
     * @access public
     * @return string
     */
    function limit() {
  return (($this->curr-1)*$this->psize).','.$this->psize;
 }

}

define ("tblPath",".\");
define ("exten",".php");
define ("fileHead","<? echo "You are wellcome!"?".">This file only for class txtTbl");
class txtTbl {
  var $innerName="";  //数据库名称
  var $innerCount;  //数据库记录数目
  var $innerFields;  //数据库字段列表数组
  var $inner_F_Count; //数据库字段数目
  var $fullName;  //完整的文件名
  var $isModify = false;  //当前记录是否被修改
  var $fileModify = false;  //数据库是否被修改
  var $innerRecorders;  //数据库记录数组
  var $curLine;  //当前记录号
  var $curArray;  //当前行数组
  var $stringDel;  //保存被删除记录
  var $sprt1;  //数据库记录间的分隔符
  var $sprt2;  //数据库字段间的分隔符
  var $innerBof = true;
  var $innerEof = false;

 

  function create($tblName,$fields,$sprt1="<---txtTbl--->n",$sprt2="<---txtTbl--->"){
 if (empty($tblName)){
  echo "The textDateBase file name not appoint.";
  return false;
 }
 $fullName = tblPath.$tblName.exten;
    if (file_exists($fullName)){
  echo "The textDateBase file is already exist.";
  return false;
 }
    if(empty($fields)){
  echo "The fields list Array is invalid.";
  return false;
 }
 $cont = implode($sprt2,$fields);
 $cont = fileHead."n".$cont;
 $fp = fopen($fullName,"w");
    fwrite($fp,$cont);
 fclose($fp);
 return true;
  }

  function drop($tblName,$sprt1="<---txtTbl--->n",$sprt2="<---txtTbl--->"){
 if (empty($tblName)){
  echo "The textDateBase file name not proveid.";
  return false;
 }
 if (!empty($this->innerName)){
  echo "Current file not closed,Please close it and try again.";
  return false;
 }
 $fullName = tblPath.$tblName.exten;
    if (!file_exists($fullName)){
  echo "The textDateBase file not exist.";
  return false;
 }
 $fp = fopen($fullName,"r");
 if (!feof($fp)){
  $readFromFile = fgets($fp);
 }
 if ($readFromFile!=fileHead."n"){
  fclose($fp);
  echo "not a valid textDataBase file.(the head is invalid.)"."n";
  return false;
 }
 $readFromFile = "";
 if (!feof($fp)) $readFromFile.= fgets($fp);
 fclose($fp);
 $readFromFile = trim($readFromFile);
 if (empty($readFromFile)){
  echo "not a valid textDataBase file.(can't find fields define.)";
  return false;
 }
 $cont = fileHead."n".$readFromFile;
 $fp = fopen($fullName,"w");
 fwrite($fp,$cont);
 fclose($fp);
 return true;
  }
 
 
  function open($tblName,$sprt1="<---txtTbl--->n",$sprt2="<---txtTbl--->"){
 if (empty($tblName)){
  echo "The textDateBase file name not proveid.";
  return false;
 }
 if (!empty($this->innerName)){
  echo "Current file not closed,Please close it and try again.";
  return false;
 }
 $this->fullName = tblPath.$tblName.exten;
    if (!file_exists($this->fullName)){
  echo "The textDateBase file not exist.";
  return false;
 }
 $fp = fopen($this->fullName,"r");
 if (!feof($fp)){
  $readFromFile = fgets($fp);
 }
 if ($readFromFile!=fileHead."n"){
  fclose($fp);
  echo "not a valid textDataBase file.(the head is invalid.)"."n";
  return false;
 }
 $readFromFile = "";
 while (!feof($fp)) $readFromFile.= fgets($fp);
 fclose($fp);
 $readFromFile = trim($readFromFile);
 if (empty($readFromFile)){
  echo "not a valid textDataBase file.(can't find fields define.)";
  return false;
 }
    $this->innerRecorders = explode($sprt1,$readFromFile);
 $this->innerCount = count($this->innerRecorders) - 1;
    $this->innerFields = explode($sprt2,$this->innerRecorders[0]);
    $this->innerFieldsCount = count($this->innerFields);

 $this->innerName = $tblName;
 $this->sprt1 = $sprt1;
 $this->sprt2 = $sprt2;

 if ($this->innerCount==0){
  $this->curLine = 0;
  $this->innerEof = true;
 }else{
  $this->curLine = 1;
//  if ($this->innerCount==1) $this->innerEof = true;
        if (!$this->initRec()) return false;
 }

 return true;
  }

  function close(){
 if (empty($this->innerName)) return true;
 //save modify
 $isModify= false;
    if ($this->isModify){
  $this->saveModify();
  $isModify= true;
 }
 if(isset($this->stringDel)){
  $isModify= true;
  $delNo= explode(",",$this->stringDel);
  foreach($delNo as $no){
   $no= (integer) $no;
   unset($this->innerRecorders[$no]);
  }
 }
 if ($isModify||$this->fileModify){
  $recorders= implode($this->sprt1,$this->innerRecorders);
  $recorders= fileHead."n".$recorders;
  $fp = fopen($this->fullName,"w");
  fwrite($fp,$recorders);
  fclose($fp);
 }
 $this->innerName="";
 unset($this->innerRecorders);
 unset($this->curArray);
  }

  function next(){
   if ((!$this->innerEof)&&(!empty($this->innerName))){
    if($this->curLine==$this->innerCount){
     $this->innerEof = true;
     return true;
    }
    $this->saveModify();
    $this->curLine++;
    if ($this->innerBof) $this->innerBof = false;
    $this->initRec();
   }
   return false;
  }
 
  function prev(){
   if ((!$this->innerBof)&&(!empty($this->innerName))){
    $this->saveModify();
    $this->curLine--;
    if ($this->curLine == 1)
     $this->innerBof = true;
    if ($this->innerEof) $this->innerEof = false;
    $this->initRec();
   }
  }

  function first(){
    if ($this->innerBof||empty($this->innerName))
  return false;
    $this->saveModify();
 $this->curLine = 1;
 $this->innerBof= true;
 $this->innerEof = false;
 $this->initRec();
 
  }
 
  function end(){
    if ($this->innerEof||empty($this->innerName))
  return false;
    $this->saveModify();
 $this->curLine = $this->innerCount;
 $this->innerEof= true;
 $this->innerBof = false;
 $this->initRec();
 
  }
 
  function eof(){
   if (empty($this->innerName)){
    return false;
   }else return $this->innerEof;
  }

  function bof(){
   if (empty($this->innerName)){
    return true;
   }else return $this->innerBof;
  }

  function recNo(){
   return $this->curLine;
  }

  function recCount(){
   return $this->innerCount;
  }

  function fieldsCount(){
   if (empty($this->innerName)){
    return false;
   }else return $this->inner_F_Count;
  }

  function getValue($field){
 if ($this->curLine==0||empty($this->innerName)){
  echo "Can't read current record,maybe not in use or no record.";
  return false;
 }
 $field= $this->chkField($field);
    if ($field==-1){
  return false;
 }
 return $this->curArray[$field];
  }

 
  function setValue($field,$value){
    if ($this->curLine==0||empty($this->innerName)){
  echo "Can't read current record,maybe not in use or no record.";
  return false;
 }
 $field= $this->chkField($field);
 if ($field==-1){
  return false;
 }
 $this->curArray[$field]= $value;
 $this->modify= true;
  }
 
  function display($shownon=0,$sprt1="<td>",$sprt2="</td>",$sprt3="<tr>",$sprt4="</tr>"){
 echo $sprt3;
 foreach($this->curArray as $v){
  if($shownon==1&&empty($v)) $v= "noValue";
  echo $sprt1.$v.$sprt2;
 }
 echo $sprt4;
  }

  function location($field,$keyValue){
    $field=$this->chkField($field);
 if ($field==-1) return false;
 for($i=$this->curLine;$i<=$this->innerCount;$i++){
  if($this->curArray[$field]==$keyValue){
   return true;
  }
  $this->next();
 }
 return false;
  }
 
  function del($recNo=-1){
 if($this->curLine==0) return false;
 $vartype= gettype($recNo);
 if($vartype!="integer"){
  echo "del error:check ur para type.";
  return false;
 }
    if ($recNo==-1){
  $recNo=$this->curLine;}
 elseif ($recNo>$this->innerCount||$recNo<1){
  echo "del error:out over the rang.";
  return false;
 }
 if (!$this->chkDel($recNo)){
  if(isset($this->stringDel)){
   $this->stringDel.=(','.$recNo);
  }else $this->stringDel = (string) $recNo;
 }else return false;
  }
  
  function append($fields=""){
 $this->saveModify();
 for($i=1;$i<=$this->innerFieldsCount;$i++)
  $newRec[] = "";
    if(!empty($fields)){
  foreach($fields as $k=>$v){
   $k= $this->chkField($k);
   if ($k==-1){
    return false;
   }
            $newRec[$k]= $v;
  }
 }
 $this->innerCount++;
 $this->curLine = $this->innerCount;
 $this->innerBof = false;
 $this->innerEof = true;
 unset($this->curArray);
 $this->curArray = &$newRec;
 $this->isModify = true;
  }
 


 //保存修改
 function saveModify(){
  if($this->isModify){
   $this->innerRecorders[$this->curLine]= implode($this->sprt2,$this->curArray);
   $this->isModify = false;
   $this->fileModify= true;
  }
 }

 //当指针发生变化时,初始化当前记录数组
 function initRec(){
  $this->curArray = explode($this->sprt2,$this->innerRecorders[$this->curLine]);
  if (count($this->curArray)!=$this->innerFieldsCount){
   echo "The Current Recorder fields count unequal to Table's.n File will close.";
   $this->close();
   return false;
  }
  return true;
 }


 //输出当前记录信息,设计为调试用
 function ddisplay(){
  if ($this->innerCount==0) return false;
  foreach($this->innerFields as $v) echo $v."----";
  echo "<br>";
  foreach($this->curArray as $v) echo $v."---";
 }

 //检查记录是否已被删除
 function chkDel($key){
  if (empty($key)&&$key!=0){
   echo "the key not appoint.";
   return false;
  }
  if (!isset($this->stringDel)){
   return false;
  }
  if (ereg("(^|,)".$key."(,|$)",$this->stringDel)){
   return true;
  }
  return false;
 }

 //检查提交的字段名是否合法.
 function chkField($field){
  if (empty($field)&&($field!=0)){
   echo "the field not appoint.";
   return -1;
  }
  $vartype = gettype($field);
  switch ($vartype) {
   case "integer":
    if ($field>=$this->innerFieldsCount){
        echo "the field is large than fieldscount";
        return -1;
    }elseif($field<0){
     echo "the field is less than 0";
     return -1;
    }
    return $field;
  case "string":
   foreach ($this->innerFields as $k=>$v) if ($field==$v) return $k;
   echo "the field name not found.";
   return -1;
  default:
   echo "the field is invalid.";
   return -1;
  }
 }

}

class Import{

 var $csv_fields=array(); //fields in csv to care about...
 var $csv_file; //file to open
 var $csv_data; //data in file
 var $csv_array = array(); //array of data in file
 var $csv_all_fields = array(); //all the field names in the csv file
 var $csv_data_all = array(); //all the data
 var $csv_data_keyed = array(); //all the data
 var $tmp_array=array();
 var $mysql_array=array();
 var $table; //table to insert into
 var $mysql_link; //database
 var $instructions=array(); //sql and default settings
 var $instruct_functions = array(); //function calls
 var $debug=0; // show debug information - step by step messages
 var $return_debug=0; // return debug information instead of echoing it
 var $vals_per_insert=100; //number of values to add per insert statement of SQL
 var $format="linux";
 var $linebreak_char="n";
 var $delimit_char = ",";
 var $use_external_csv_header_file = 0;
 var $external_headers="";
 
 function Import(){
  echo "n";
  return(TRUE);
 }

 var $resetProgress=0;
 function reset_class_state(){
  $this->dmsg("Resetting class state", 2);
  $this->csv_data_all = array();
  $this->csv_fields = array();
  $this->csv_data_keyed = array();
  $this->tmp_array = array();
  $this->mysql_array = array();
  $this->instructions = array();
  $this->instruct_functions = array();
  $this->error_messages = "";
  $this->output_sql = "";
  $this->resetProgress=1;
  $this->dmsg("Ready for new table and data definitions", 2);
 }

 function set_delimit_char($ch){
  $this->delimit_char = $ch;
  $this->dmsg("Set delimiter character to $ch", 2);
 }

 function debug($d=0,$r=0){
  $this->debug=$d;
  $this->return_debug=$r;
 }

 var $y=1;
 var $error_messages="";
 var $debug_level = 1;
 function set_debug_level($dl=1){
  $this->debug_level = $dl;
 }

 function dmsg($string, $dlvl=1){
  global $PHP_SELF;
  //debug level - 1-4 //1 is status messages only - 4 is full debugging
  if($dlvl <= $this->debug_level){
   if($this->debug){
    if(!$this->return_debug){
     if($PHP_SELF){
      echo "&bull; ".$string."<BR>n";
     }else{
      echo "n# $string ";
     }
    }else{
     $this->error_messages .="# $string <BR>n"; 
    }
    $this->y++;
   }
  }
 }

 var $terminal_width=100;
 var $queries_per_dot = 20;

 function progress_guess(){
  $calculations_to_perform = `wc -l $this->csv_file`;
  $funcs_per_row = count($this->instruct_functions);
  $total_function_calls = $calculations_to_perform * $funcs_per_row;
  $this->queries_per_dot = round($total_function_calls / 100);
  $this->dmsg("functions: $total_function_calls function calls to be made - dots at $this->queries_per_dot calls per dot", 3);
 }

 function set_terminal_width($w){
  $this->terminal_width=$w;
 }

 function set_resetProgress($on=1){
  $this->resetProgress=1;
 }
 function show_progress_meter(){
  static $count=0;
  static $first=1; 
  static $ticker=0;

  //reset class state triggers this action
  if($this->resetProgress){
   $count=0;
   $first=1;
   $ticker=0;
   $this->resetProgress=0;
  }

  if($this->debug){
   if($count == 0 && $first){
    echo "n#";
    $first=0;
   }

   if($count > $this->terminal_width ){
    echo "n#";
    $count=0;
   }
      //queries per dot
   if($ticker == $this->queries_per_dot){
    echo ".";
    $ticker=0;
    $count++;
   }else{
    $ticker++;
   }
  }
 }

 function blank_error_messages(){
  $this->error_messages = "";
 }

 function get_error_messages(){
  return($this->error_messages);
 }

 function add_field_alias($csv_field, $mysql_field){
  //add element to array
  $this->csv_fields[$csv_field] = $mysql_field;
  if(ereg("^TMP__", $mysql_field)){
   $this->dmsg("added temporary field alias $csv_field --> $mysql_field", 2);
  }else{ 
   $this->dmsg("added field alias $csv_field --> $mysql_field", 2);
  }
 }

 //only call this after calling read_csv_file - otherwise array will be missing.
 //ALSO - ONLY CALL AFTER create_csv_data_array() has been called for any initial add_field_alias values.
 //otherwise these fields are missing from the end array but no warnings are dipsplayed!! :(
 function duplicate_field($csv_field, $mysql_field){
  
  if(!is_array($this->mysql_array)){
   echo "Run read_csv_file($file) first to create necessary arrays"; die();
  }

  reset($this->mysql_array);
  while(list($key, $this->field) = each($this->mysql_array)){
   $this->mysql_array[$key][$mysql_field] = $this->csv_data_all[$key][$csv_field];
  }
  reset($this->mysql_array);
  $this->dmsg("duplicated field $csv_field --> $mysql_field", 1);
 }

 function use_external_headers($headerfile){
    
   $this->dmsg("Reading in external csv headers from $headerfile.", 2);
   if(file_exists($headerfile)){
    $fd = fopen($headerfile, "r");
    $this->external_headers = fread($fd, filesize($headerfile));
    $this->external_headers = trim($this->external_headers);
    fclose($fd);
     $this->use_external_csv_header_file = 1;
   }else{
    $this->dmsg("Error - csv header file $headerfile does not exist!" );
    die();
   }

   $this->dmsg("Got headers:n $this->external_headers", 2);
 }

 //clean file will replace commas quotes and apostrophies with safe alternatives -
 //create_sql knows about the aliases and flips them back in the final sql output
 function clean_file($text){
  $rows = explode($this->linebreak_char,$text);
  $return = "";
  while(list($key,$val)=each($rows)){
  //replace commas apostrophies and quotes.... these are flipped back to propper values in the create_sql function 
   $val = preg_replace("/,"(.*)([,])(.*)",/", ',"\1&comma;\3",',  $val, -1);
   $val = str_replace("""", "&quote;", $val);
   $val = str_replace("'", "&appos;", $val);
   $return .= $val."n";
  }
  return($return);
 }

 var $pages = array();
 function find_xls_pages($file){
  $command = " xlhtml -dp -asc $file";
  $xls_detail = `$command`;
  
  $this->dmsg($xls_detail);

 }

 //function can read xls files and create the necessary arrays from that (by using xlhtml application to craete a csv in /tmp)
 function read_xls_file($file){
  //use xlhtml to convert...
  $this->dmsg("checking if xlhtml is installed...", 3);
  $xlhtml_check = `which xlhtml 2>/dev/null`;
  if(strlen($xlhtml_check)==0){
   $this->dmsg("You must install xlhtml to be able to import xls files directly into csv2mysql", 1);
   die("n# Script Endedn");
  }
  $this->dmsg("$xlhtml_check");
  $tmpfilename="/tmp/TMPCSV2MYSQL.CSV";

  $this->find_xls_pages($file);

  $command = "$xlhtml_check -csv -xp:0 $file > $tmpfilename";
  $this->dmsg("Running command $command");
  exec($command);
  $this->read_big_csv_file($tmpfilename);
 }

 var $fd;
 function read_csv_file($file){
  //call better function - reads in file line by line
  $this->read_big_csv_file($file);
 }

 var $buffer;
 var $csvfields;
 var $csv_all_possible_fields = array();
 var $csvFields = array();
 function  read_big_csv_file($file){
  $this->dmsg("Reading data from csv file: $file", 1);
  $this->csv_file = $file;
  
  if(!$this->fd=fopen($this->csv_file, "r")){
   echo "Unable to open csv filenn"; die();
  }

  /*
  $x=0;
  while(!feof($this->fd)){
   $this->buffer = fgets($this->fd, 4096);
   $this->csv_data .= $this->buffer; 
   $x++; 
  }
  */

  //creates an array called data....
  while($data = fgetcsv($this->fd, 1000, $this->delimit_char)){
   $num = count($data);
   $count=1;
   foreach($data as $cell){
    $cell = str_replace(""", "&quote;", $cell);  
    $cell = str_replace("'", "&appos;", $cell);  
    $cell = str_replace(",", "&comma;", $cell);
    $this->csv_data .= $cell;
    if($count < $num){ 
     $this->csv_data .= $this->delimit_char;
     $count++;
    }
   }
   $this->csv_data .= $this->linebreak_char;
  }

  //die($this->csv_data);
  //clean file will replace commas quotes and apostrophies with safe alternatives -
  //create_sql knows about the aliases and flips them back in the final sql output
  //$this->csv_data = $this->clean_file($this->csv_data);

  //if we are using an external header file then add the headers to the top of the read in data for simplicities sake...
  if($this->use_external_csv_header_file){
   $this->csv_data = $this->external_headers."n".$this->csv_data; 
  }
    /* create array of the field names */
 
 
  $this->csvfields = explode($this->linebreak_char, $this->csv_data);
  $this->csv_all_possible_fields = $this->csvfields[0];
   //explode these on commas
  $this->csvfields = explode($this->delimit_char, $this->csv_all_possible_fields);
  foreach($this->csvfields as $field){
   $this->csvFields[] = addslashes($field); 
  }
  
   

  $this->dmsg("Finished reading data from csv file", 2);
 }

 var $tmp;
 function set_format($format){
  $this->format = $format;
  if($format == "win"){
   $this->linebreak_char = "rn";
   $this->tmp = "\r\n";
  }else{
   $this->linebreak_char = "n";
   $this->tmp = "\n";
  }
  //$this->dmsg("Line break format set to ".addslashes($this->linebreak_char));
  $this->dmsg("Line break format set to $this->tmp", 2);
 }

 var $lines; 
 var $stripQuotes = 1;
 function setStripQuotes($on=1){
  $this->stripQuotes = $on;
 }

 //function will create csv_data_all array - keyed on csv field names holding values.
 function create_csv_data_array(){


  if(empty($this->csv_data)){
   echo "No data in csv file $this->csv_filen"; die();
  }

  $this->lines = array();
  $this->csv_data_all = array();
 
  $this->dmsg("Started to create data array", 1);
  $this->lines = explode($this->linebreak_char, $this->csv_data);
  foreach($this->lines as $line){
   if(!empty($line)){
    $values = explode($this->delimit_char, $line);

    //strip the " tags wrapping the strings...
    foreach($values as $k=>$v){
     if($this->stripQuotes){
      $len = strlen($v)-1;
      //are the first and last characters quotes?
      $v = stripslashes($v);
      if(ereg("^".+"$", $v)){
       //if so replace them with spaces and then trim them off
       //$v[0] = " ";
       //$v[$len] = " ";
       //$v = trim($v); 
       //$v = str_replace(""", "", $v);

      } 

     }
     $v = str_replace(""", "", $v);
     //$values[$k] = addslashes($v);
     $values[$k] = $v;
    }
    $this->csv_array[] = $values;
   }
  }
  $this->csv_all_fields = $this->csv_array[0];

  //skip line 1 as this is the csv definition then run through the array -
  //create a new array keyed on the field names of the csv and holding the values
  $count=0;
  reset($this->csv_array);
  while(list($foo,$el)=each($this->csv_array)){
   if($count>0){
    foreach($el as $key=>$val){
     $this->csv_data_keyed[$this->csv_all_fields[$key]]=$val;  
    }
    $this->csv_data_all[] = $this->csv_data_keyed;
   }
   $count++;
  }
  reset($this->csv_array);

  $this->dmsg("finished creating initial data array", 2);
  $this->convert_array_to_mysql_keys();
 }

 function convert_array_to_mysql_keys(){

  reset($this->csv_data_all);
  $this->dmsg("creating keyed data array", 2);
  //loop through all specified fields - create new array keyed on the specified aliases.
  reset($this->csv_data_all);

  while(list($foo,$data)=each($this->csv_data_all)){

   foreach($this->csv_fields as $key=>$field){
    $this->tmp_array[$field] = $data[$key];
   }
   $this->mysql_array[] = $this->tmp_array;

  }
  reset($this->csv_data_all); 
 }


 var $sql;
 var $result; 
 var $tbl_structure;
 var $mysqlFields = array();
 //specify database table to insert into.....
 function specify_table($table){
  $this->table = $table; 
  $this->dmsg("looking at database table $table", 2);
  $this->sql = "desc  $this->table";

  $this->result = mysql_query($this->sql, $this->mysql_link) or die(mysql_error());
  while($rows = mysql_fetch_array($this->result, MYSQL_ASSOC)){
   $this->tbl_structure[] = $rows; 
   $this->mysqlFields[] = $rows['Field'];
  }
  $this->dmsg("finished looking at table $table", 2);
 }

 //adds a static alias - if you always want field "foobar" to say "hello" then add_static_alias("foobar", "hello"); will do this for every row
 function add_static_alias($field, $value){
  $this->add_db_instruction($field, $value);
 }

 //add an sql instruction for a particular field
 function add_db_instruction($field, $sql, $key=""){
  $instruct['field'] = $field;
  $instruct['sql'] = $sql;
  $instruct['select_key'] = $key;
  $this->instructions[]=$instruct;
  $this->dmsg("added db instruction or static alias for $field", 2);
  $this->set_resetProgress();
 }


 function add_function_instruction($field, $functionname, $args){
  $instruct['field'] = $field;
  $instruct['function_name'] = $functionname;
  $instruct['args'] = $args;
  $this->instruct_functions[] = $instruct;
 
  $this->dmsg("added function instruction for $field", 2);
  $this->set_resetProgress();
 }

 //execute function instructions
 var $call;
 function get_function_instruction_values(){
  $this->progress_guess();
  $this->dmsg("calculating values for function instructions", 2);
  reset($this->mysql_array);
  while(list($key,$element)=each($this->mysql_array)){
   
   foreach($this->instruct_functions as $function){

    $this->call = "$function_result = ".$function['function_name'];

    //split the arguments up to calculate values...
    $args = explode(",", $function['args']);
    $arg_call = "";

    $num_args = count($args)-1;
    $count=0;

    //get the arg values
    foreach($args as $arg){
     $arg = trim($arg);
     $arg_call.=""".$element[$arg].""";
     if($count<$num_args){
      $arg_call .= ",";
     }
     $count++;
    }
  
    //add arg values to end of function
    $this->call.="(".$arg_call.");";

    //eval the created function call - variable function_result populated with return value
    //die($this->call);
    $this->dmsg("Run function instruction : $this->call", 4);
    $this->show_progress_meter();
    eval($this->call);

    //add the value to the mysql_array
    $this->mysql_array[$key][$function['field']] = $function_result;
   } 
  }
  reset($this->mysql_array);
 }

 //execute db instructions
 var $product_id;
 function get_instruction_values(){
 
  $this->dmsg("calculating values for db instructions", 2);
  
  reset($this->mysql_array);
  while(list($key,$element)=each($this->mysql_array)){

    foreach($this->instructions as $ins){
     if(eregi("SELECT", $ins['sql'])){
       $ins['sql'] = stripslashes($ins['sql']);
       $this->select_key = $ins['select_key'] ;
      
       //if we havent yet got a value for this...
       if(!isset($this->mysql_array[$key][$ins['field']])){
        $this->mysql_array[$key][$ins['field']] = $this->run_sql_query($ins['sql'], $element[$this->select_key]);
       }
     }else{
      $this->mysql_array[$key][$ins['field']] = $ins['sql'];
     }
    }
   $this->show_progress_meter();
  }
  reset($this->mysql_array);
 }

 var $runsql;
 var $dbrows;
 var $dbkey;
 //not what you'd think function -- this is for evaling code - for the instructions.
 //TODO rename function to a more logical name reflecting what it does better.
 function run_sql_query($sql, $dbkey){

  $this->runsql = stripslashes($sql);
  $this->dbkey = $dbkey;
 
  //eval the code into this->runsql -
  //this makes the dbkey get populated with a value instead of being a string 

  eval("$this->runsql = "$this->runsql";");
  $this->dmsg("running sql query..$this->runsql", 4);

  //run query and return result
  $this->result = mysql_query($this->runsql, $this->mysql_link) or die(mysql_error());

  while($rows = mysql_fetch_array($this->result, MYSQL_ASSOC)){
   $this->dbrows = $rows['result']; 
   $this->dmsg("$this->runsql returns: $this->dbrows", 4);
  }

   $this->dmsg("$this->runsql returns: $this->dbrows", 4);
  
  return($this->dbrows);
 }

 //connect to the database
 function db_connect($host, $user, $pass, $db){
  $this->dmsg("connecting to database", 2);
  $this->mysql_link = mysql_pconnect("$host", "$user", "$pass") or die(mysql_error());
  if($this->mysql_link){
   mysql_select_db($db);
  }  
 }

 var $specified_fields=array();
 var $sql_error=0;
 var $error_fields = array();

 //check that all the fields required for the table are present and correct....
 function validate_sql(){
  $this->dmsg("validating array elements to generate sql from", 1);

  reset($this->mysql_array);
  //step through elements in array, foo is an unused variable.
  while(list($foo,$this->element)=each($this->mysql_array)){
   
   //dont mind a foreach here- tiny array to play with...
   foreach($this->element as $this->field=>$val){
    //make an array of the field names that have been specified...
    if(!in_array($this->field, $this->specified_fields)){
     $this->specified_fields[] = $this->field;
    }
   }

  }
  reset($this->mysql_array);

  //upon errors this will be true - causing die below to spring to life...
  $this->sql_error=0; 

  //loop through the tables fields - create array
  foreach ($this->tbl_structure as $this->field){

   //if the field is not in the array of specified fields and it has no default value
   // and the field in question is not a primary key- moan
   if(!in_array($this->field['Field'], $this->specified_fields)
     && ($this->field['Default']=="")
     && ($this->field['Key'] != 'PRI')
     && ($this->field['Extra'] != 'auto_increment')
     && ($this->field['NULL'] != "YES" ) ){

    $this->dmsg( "{$this->field['Field']} has no default and you have not specified a value for this field.", 1);
    $this->sql_error=1; 
    $this->error_fields[] = $this->field['Field'];

   }else{
    $this->dmsg( "{$this->field['Field']} has been verified.", 4);
   }
  }

  #IF THIS VAR IS SET THEN SOMETHING ERRORED - REPORT THIS WITH A MESSAGE.
  if($this->sql_error){
   echo $this->error_messages;
   $this->csv_data_all = array();

   if(function_exists("render_page_head")){
    echo render_page_head();
   }
   $erst="";
   foreach($this->error_fields as $f){
    $erst.="Field ".$f." has no default <BR>";
   }
   die("n$erst Please specify values for the missing fields please add definitions for these fields.");
  }

 }
 
 var $element;
 var $output_sql;
 var $insert_into;
 var $values;
 var $all_values = array();
 var $insert_line;

 function create_sql($show=0){
  //check all array elements are present and correct...

  $this->validate_sql();

  $this->dmsg("creating sql", 1);


#TODO: THIS IS NOT VERY CLEVER MEMORY MANAGEMENT - IT WOULD BE BETTER NOT TO CREATE
# EACH VALUE LINE AND SAVE IN AN ARRAY - IF THERE ARE 10,000 RECORDS THIS WILL KILL
# PHP AND THE LINUXBOX - LOCKUP COMPLETELY ALT+SYSREQ+S+U+B TO RECOVER MACHINE!!!!
# OUTPUTTING EACH LINE AS IT WAS CREATED WOULD BE MUCH LESS PROCESSOR INTENSIVE.
 
  $this->values = "";
  //loop through each row to be entered
  reset($this->mysql_array);
  $this->all_values = array();
  while(list($foobar,$this->element)=each($this->mysql_array)){

   //loop through each field name and value
   $num=count($this->element)-1;
   $x=0;
    //blank data
    $this->insert_into = "";
    $this->values = "(";

   foreach($this->element as $field=>$val){
    //do not include temporary fields - these can be used for the function fields
    if(!ereg("^TMP__", $field )){
     $val = str_replace("&quote;", """, $val);
     $val = str_replace("&comma;", ",", $val);
     $val = str_replace("&appos;", "'", $val);
      $this->insert_into .= $field." ";
      $this->values .= "'$val' ";
      if($x<$num){ 
       //capture field names
       $this->insert_into.=",";
       $this->values .= ", ";
      }
    }
    $x++; 
   } 
   $this->values .= ")";
   $this->all_values[] = $this->values;

 
  }
 
  //create insert line of the sql
  $this->insert_line = "REPLACE INTO $this->table ( $this->insert_into ) VALUESn ";
  $this->output_sql = $this->insert_line;

  $num=count($this->all_values)-1;
  $x=0;
  $i=1;

  //loop through the list of VALUES "(bla,bla,bla)" in array adding each to sql
  //when vals_per_insert is reached close sql statement and add another insert line

  reset($this->all_values);

  while(list($foo,$v)=each($this->all_values)){ 

   //only add specified number of values per insert statement (vals_per_insert)
   if($i== $this->vals_per_insert){
    $this->output_sql .= $v.";nn".$this->insert_line;
    $i=1; 
   } 

   else{ 
    $this->output_sql .= " $v ";

    if($x<$num){
     $this->output_sql .= ",n";
    }
   }
   $x++;
   $i++;
  }
  reset($this->all_values);
  reset($this->mysql_array);

  //finish the sql statement
  $this->output_sql .= ";";
  if($show){
   echo "n##########################################################n";
   echo "# SQL Created by Csv2MySQL.1.1.inc n";
   echo "# CyBeRtIlL LeGaCy ImPoRtAtIoN ToOl n";
   echo "# ".date("D d-m-Y H:i:s", time())."n";
   echo "# CSV File: $this->csv_file n";
   echo "##########################################################n";
   echo "nn".$this->output_sql."n";
  }
  else{
   return($this->output_sql);
  }
 }

 var $keys;
 //just a little debugging function
 function show_definitions($tbl=1, $return=0){
  if(!$tbl){
   ds($this->mysql_array);
 
   #BELOW ARE JUST SOME MORE OPTIONAL DUMPS FOR DEBUGGING
   //ds($this->csv_fields);
   //ds($this->csv_data_all);
   //ds($this->tbl_structure);
   //ds($this->instructions);
   //echo nl2br($this->output_sql);
  }else{
   if(!$return){
    #DEBUG JARGON - "FOR THOSE THAT KNOW" ;)
     echo "<pre>";
     $d=new display($this->csv_data_all);
     $d->make_layout(1);
     $d=new display($this->mysql_array);
     $d->make_layout(1);

     #OPTIONAL DEBUG DUMPS
     //$d=new display($this->instructions);
     //$d->make_layout(1);
     //$d=new display($this->instruct_functions);
     //$d->make_layout(1);
     //$d=new display($this->tbl_structure);
     //$d->make_layout(1);
     //echo nl2br($this->output_sql);
     echo "</pre>";

   }else{
    #RETURN DATA TO FUNCTION CALLER... 
    //get the array keys 
    $keys = array_keys($this->mysql_array[0]);
    $this->keys = $keys; 
    //go through keys - grab 5 rows from big array - this is to display
    //to the user what they are doing while adding functions etc. - without
    //taking up potentially 1000's of lines...
    foreach($keys as $key){
     $x=0;
     while($x<5){
      $sample[$x][$key] = $this->mysql_array[$x][$key];
      $x++;
     }
    }
    $d=new display($sample);
    $string = $d->make_layout(0);
    return("<pre>".$string."</pre>");
   }
  }
 }

 function return_csv_fields(){
  return($this->csvFields);
 }
 
 function return_mysql_fields(){
  return($this->mysqlFields);
 }

 function return_mysql_key_fields(){
  //return(array_keys($this->mysql_array[0]));
  return($this->keys);
 }
}

 

?>
                                                                                                                                                                                                       htmltablecreation.inc                                                                               0100400 0177776 0177776 00000013216 07561045034 015071  0                                                                                                    ustar   nobody                          nogroup                                                                                                                                                                                                                <?php

//////// sample array to pass to class //////////
/*
$stuff = array("0" => array(
            "product_id" => "00001",
            "actual_unit_cost"  => "99.99",
            "retail_unit_cost" => "124.99",
            "quantity"   => "5"
           ),
      "1" => array(
            "product_id" => "00002",
            "actual_unit_cost" => "699.99",
            "retail_unit_cost" => "750.00",
            "quantity"   => "3"        
          )
      );
*/


class display {
 var $widths = array();
 var $biggest = array();
 var $data = array();
 var $dis;
 var $divider;
 var $rows;
 var $emptyset=FALSE;
 var $write; //echo the output
 var $ascii_output;
 var $finalhtmltable;
 var $stylesheet;
 
 var $borderwidth = 0;
 var $bordercolor = "#000000";
 var $cellpadding = 2;
 var $cellspacing = 1;
 

 function calculate_widths($array){
  if(empty($array)){
   //check that there is some data to display
   $this->emptyset=TRUE;
   return(false);
  }
  //loop through each row
  $this->data = $array;
  $x=0;
  if(is_array($array)){
   foreach($array as $a){
    while(list($key, $val) = each($a)){
      $this->widths[$x][$key] = strlen($val);
    }
    ++$x;
   }
  }
  $this->biggest = $this->get_longest_only();
  return($this->widths);
 }

 function get_longest_only(){
  $x=0;
  $array = $this->widths;
  foreach($array as $a){
   while(list($key, $val) = each($a)){
     if($val > $this->biggest[$key] || empty($this->biggest[$key])){ 
      $this->biggest[$key] = $val;
     }
     if(strlen($key) > $this->biggest[$key]){
      $this->biggest[$key] = strlen($key);
     }
   }
   ++$x;
  }
  return($this->biggest);
 } 

 function make_layout($write=1){
  $this->write = $write;
  if($this->emptyset){
   return("Empty set (0.00 hehehe)n");
  }
   $first="+"; 
   while(list($key, $val) = each($this->biggest)){

   $dis.="+";
    for($x=0;$x<$this->biggest[$key];$x++){
     $first .= "-";
    }
    $first.="+";
    $s="|".ucwords(str_replace("_", " ",$key));
    if(strlen($s)<= $this->biggest[$key]){
     for($x=strlen($s);$x<=$this->biggest[$key];$x++){
      $s.=" ";
     }
    }
    $second.=$s;
   }
  $this->divider = $first;
  $re = $first."n".$second."|n".$first."n";
  $re.=$rows; 

  $this->rows = $this->make_body();
  $re.=$this->rows;
  if($this->write){
   //write the output to the webpage
   //echo "<pre>".$re."</pre>";
   echo "".$re."";
  }
  $this->ascii_out = $re;
  return($re);
 }

 function create_stylesheet($bg="ededed", $fontcol="000000", $fontsize="x-small", $bg2="444444", $fontcol2="ffffff", $fontsize2="x-small"){
  $this->stylesheet = "
   <STYLE type='text/css'>
   <!--
    .column-data { background:$bg; color:$fontcol; font-size:$fontsize; }
    .table-header { background:$bg2; color:$fontcol2; font-weight:bold; text-align:center; font-size:$fontsize2 }
   //-->
   </style>";
 }

 function make_body(){
  if(is_array($this->data)){
   foreach($this->data as $row){ 
    while(list($key, $val)=each($row)){

    if(is_array($val)){
     $out[0]=$val;
     $tr = new display($out);
     $tr->make_layout(0);
     $tr->set_borderwidth($this->borderwidth);
     $tr->set_cellpadding($this->cellpadding);
     $tr->set_cellspacing($this->cellspacing);
     $tr->set_bordercolor($this->bordercolor);  
     $val = "<Table><TR><TD> ".$tr->make_html_table()."</TD></tR></tAble>";
    }
     $r .= "|".$val;
     if(strlen($val)<= $this->biggest[$key]){
      for($x=strlen($val);$x < $this->biggest[$key]; $x++){ 
       $r.=" ";
      }
     }
    }
    $r.="|n";
   } 
  } 
  $r.=$this->divider."n";
  return($r); 

 }

 function get_divider(){
  return($this->divider);
 }
 
 function display($stuff){
   //constructor function
   $this->widths = $this->calculate_widths($stuff);
 }

 function set_borderwidth($wid){
  $this->borderwidth = $wid;
 }

 function set_cellpadding($pad){
  $this->cellpadding=$pad;
 }
 
 function set_cellspacing($spac){
  $this->cellspacing=$spac;
 }

 function set_bordercolor($col){
  $this->bordercolor=$col;
 }
 function make_html_table(){
  //converts ascii display into a proper html table
  $text = $this->ascii_out;   

  $rows = explode("n", $text);
  $x=0;
  foreach($rows as $row){
   $last = strlen($row);
   $class = "column-data"; 
   if($x==1){ 
    $class = "table-header";
   }
   if(!ereg("^+-*", $row) && strlen($row)>0){
    $row = "<TR>n <td class='$class' align='center' valign='middle'>".$row;
    $row .= "</td>n</TR>n";
    $row = str_replace("+", "</td><td class='$class' align='center'>", $row);
    $row = str_replace("|", "</td><td class='$class' align='center'>", $row);
    $row = str_replace("<td class='$class' align='center'></td>", "", $row); //remove any blanks
    $row = str_replace("<td class='$class' align='center' valign='middle'></td>", "", $row); //remove any blanks
    $htmloutput.=$row;
   }
   $x++;
  }

  $style = $this->stylesheet;
  $htmloutput = $style."n<TABLE border='".$this->borderwidth."' bordercolor='".$this->bordercolor."' cellpadding='".$this->cellpadding."' cellspacing='".$this->cellspacing."'>n ".$htmloutput."n</TABLE>";

  $this->finalhtmltable = $htmloutput;
  return($htmloutput); 
 }

 function returnhtml(){
  return($this->finalhtmltable);
 }
 function parsehtml(){
  echo $this->finalhtmltable;
 }
}
   
  

//$t = new display($stuff);
//$t->make_layout(0);
//echo $t->make_html_table();

/*
$d = new display($stuff);
$d->make_layout(0);
$d->set_borderwidth(0);
$d->set_cellspacing(1);
$d->set_cellpadding(2);
$d->make_html_table();
$d->parsehtml();
*/


?>

[!--infotagslink--]

相关文章

  • php KindEditor文章内分页的实例方法

    我们这里介绍php与KindEditor编辑器使用时如何利用KindEditor编辑器的分页功能实现文章内容分页,KindEditor编辑器在我们点击分页时会插入代码,我们只要以它为分切符,就...2016-11-25
  • 百度网盟和google网盟推广那种效果好

    专做了百度和google的网盟推广以作推广效果的评估比较。百度的周期为6天,google为4天。   从百度的统计数据可以看出这六天的点击次数总共为464,平均点击花费了0.30元...2017-07-06
  • 自己动手写的jquery分页控件(非常简单实用)

    最近接了一个项目,其中有需求要用到jquery分页控件,上网也找到了需要分页控件,各种写法各种用法,都是很复杂,最终决定自己动手写一个jquery分页控件,全当是练练手了。写的不好,还请见谅,本分页控件在chrome测试过,其他的兼容性...2015-10-30
  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   view-source:http://...2016-09-20
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • JS基于Mootools实现的个性菜单效果代码

    本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • JS实现自定义简单网页软键盘效果代码

    本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
  • jquery实现的伪分页效果代码

    本文实例讲述了jquery实现的伪分页效果代码。分享给大家供大家参考,具体如下:这里介绍的jquery伪分页效果,在火狐下表现完美,IE全系列下有些问题,引入了jQuery1.7.2插件,代码里有丰富的注释,相信对学习jQuery有不小的帮助,期...2015-10-30
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • JS实现双击屏幕滚动效果代码

    本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
  • js识别uc浏览器的代码

    其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08
  • JS日期加减,日期运算代码

    一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
  • PHP开发微信支付的代码分享

    微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
  • vue.js 表格分页ajax 异步加载数据

    Vue.js通过简洁的API提供高效的数据绑定和灵活的组件系统.这篇文章主要介绍了vue.js 表格分页ajax 异步加载数据的相关资料,需要的朋友可以参考下...2016-10-20
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • php怎么用拼音 简单的php中文转拼音的实现代码

    小编分享了一段简单的php中文转拼音的实现代码,代码简单易懂,适合初学php的同学参考学习。 代码如下 复制代码 <?phpfunction Pinyin($_String...2017-07-06
  • php导出csv格式数据并将数字转换成文本的思路以及代码分享

    php导出csv格式数据实现:先定义一个字符串 存储内容,例如 $exportdata = '规则111,规则222,审222,规222,服2222,规则1,规则2,规则3,匹配字符,设置时间,有效期'."/n";然后对需要保存csv的数组进行foreach循环,例如复制代...2014-06-07