English Sentence Loading...
英语句子加载中...
预览模式: 普通 | 列表

用php实现一个双向队列

代码实现:
下载: deque.php
  1. <?php
  2.     class deque
  3.     {
  4.         public $queue  = array();
  5.         public $length = 0;
  6.        
  7.         public function frontAdd($node){
  8.             array_unshift($this->queue,$node);
  9.             $this->countqueue();
  10.         }
  11.        
  12.         public function frontRemove(){
  13.             $node = array_shift($this->queue);
  14.             $this->countqueue();
  15.             return $node;
  16.         }
  17.        
  18.         public function rearAdd($node){
  19.             array_push($this->queue,$node);
  20.             $this->countqueue();
  21.         }
  22.        
  23.         public function rearRemove(){
  24.             $node = array_pop($this->queue);
  25.             $this->countqueue();
  26.             return $node;
  27.         }
  28.        
  29.         public function countqueue(){
  30.             $this->length = count($this->queue);   
  31.         }
  32.     }
  33. ?>


这道题从难度上讲其实不是很难,它主要考察了phper以下几个方面的技能:
1. 当然是双向队列的定义,这个就不多做解释了。
2. 考察对函数是否熟悉。
3. 考察OOP编程。
4. 考察程序员的代码规范和编程习惯。
标签: php 数据结构

php 分页类

这个分页类融合了数据库查询的功能,用起来还比较方便。下面这个是用了ADODB类来操作数据库,关于ADODB的操作,在这里就不多说了。

下载: dbclass.php
  1. <?php
  2.     /**
  3.     * FileName   : dbclass.php
  4.     * Description: Simple db class
  5.     * Author     : Liubing(liubing@eduicc.com)
  6.     */
  7.     class dbclass
  8.     {
  9.         var $dblink;
  10.         var $_sql;
  11.         var $primary_key;
  12.       
  13.         function dbclass($primary_key='id')
  14.         {
  15.             $this->connectDB();
  16.             $this->primary_key = $primary_key;
  17.         }  
  18.       
  19.         function connectDB()
  20.         {
  21.             global $db_config;
  22.             if(is_object($this->dblink)) return;
  23.             $this->dblink = &ADONewConnection('mysql');
  24.             $this->dblink->PConnect($db_config["db_host"],$db_config["db_user"],$db_config["db_password"],$db_config["db_name"]);
  25.         }
  26.       
  27.         function E($sql='')
  28.         {
  29.             $sql != '' && $this->_sql = $sql;
  30.             $this->dblink->Execute("SET NAMES UTF8");
  31.             return $this->dblink->Execute($this->_sql);
  32.         }
  33.       
  34.         function Store($fields,$tb,$key='')
  35.         {
  36.             if(count($fields) == 0) return false;
  37.           
  38.             foreach($fields as $field => $value){
  39.                 $params[] = "`{$field}`='".$this->safestring($value)."'";
  40.             }
  41.             $key = intval($key);
  42.             if($key > 0){ //modify
  43.                 if($this->primary_key == '' || $key < 1) return false;
  44.                 $sql = "UPDATE `{$tb}` SET ".implode(",",$params)." WHERE `{$this->primary_key}`='{$key}'";
  45.             }else{ //add new record
  46.                 $sql = "INSERT INTO `{$tb}` SET ".implode(",",$params);
  47.             }
  48.             return $this->E($sql);
  49.         }
  50.       
  51.         function getResults($params,$tb,$orderfield='')
  52.         {
  53.             $sql = "SELECT * FROM `{$tb}` ";
  54.             if(is_array($params) && count($params) > 0){
  55.                 $sql.= " WHERE ".implode(" AND ",$params);
  56.             }
  57.             if($orderfield != '') $sql.= " ORDER BY `{$orderfield}`";
  58.           
  59.             $rs = $this->E($sql);
  60.             $offset = 0;
  61.             while(!$rs->EOF){
  62.                 $rs->fields["offset"] = ++$offset;
  63.                 $results[] = $rs->fields;
  64.                 $rs->MoveNext();  
  65.             }
  66.           
  67.             if(count($results) == 0) return false;
  68.             elseif(count($results) == 1) return $results[0];
  69.             else return $results;
  70.         }
  71.       
  72.         function getRow($key,$tb)
  73.         {
  74.             if($this->primary_key == '' || $key < 1) return false;
  75.             $params[] = "`{$this->primary_key}`='{$key}'";
  76.             $results = $this->getResults($params,$tb);
  77.             return $results;
  78.         }
  79.       
  80.         function delRow($key,$tb)
  81.         {
  82.             if($this->primary_key == '' || $key < 1) return false;
  83.             $sql = "DELETE FROM `{$tb}` WHERE `".$this->primary_key."`={$key}";
  84.             $this->E($sql);
  85.         }
  86.       
  87.         function getNum($tb)
  88.         {
  89.             $sql = "SELECT COUNT(*) AS `t` FROM `{$tb}`";
  90.             $rs  = $this->E($sql);
  91.             return $rs->fields['t'];
  92.         }
  93.       
  94.         function getMax($field,$table,$params=array())
  95.         {
  96.             $sql = "SELECT MAX(`{$field}`) AS `{$field}` FROM `{$table}` WHERE 1 ";
  97.             foreach($params as $f => $val){
  98.                 $sql.= " AND `{$f}`='{$val}'";
  99.             }
  100.             $rs = $this->E($sql);
  101.             return $rs->fields[$field];
  102.         }
  103.       
  104.         //html,mysql
  105.         function safestring($string,$mode="3")
  106.         {
  107.             switch($mode)
  108.             {
  109.                 case "0":
  110.                     break;
  111.                 case "1":
  112.                     $string = mysql_escape_string($string);
  113.                     break;
  114.                 case "2":
  115.                     $string = strip_tags($string);
  116.                     break;
  117.                 case "3":
  118.                     $string = strip_tags(mysql_escape_string($string));
  119.                     break;
  120.                 default:
  121.                     break;  
  122.             }
  123.             return $string;
  124.         }
  125.     }


  1. <?php
  2.     /**
  3.     * FileName   : pageclass.php
  4.     * Description: pagination class
  5.     * Author     : Liubing(liubing@eduicc.com)
  6.     */
  7.   
  8.     require_once dirname(__FILE__).'/dbclass.php';
  9.   
  10.     class pageclass extends dbclass
  11.     {
  12.         var $page;
  13.         var $pagesize;
  14.         var $pagesql;
  15.         var $results;
  16.         var $offset;
  17.         var $params;
  18.         var $totalpage;
  19.         var $totalnum;
  20.         var $pagelink;
  21.         var $pagerange;
  22.       
  23.         function pageclass($page=1,$params=array(),$pagesize=10)
  24.         {
  25.             dbclass::dbclass();
  26.             $page            = intval($page);
  27.             $pagesize        = intval($pagesize);
  28.             $this->page      = $page < 1 ? 1 : $page;
  29.             $this->pagesize  = $pagesize < 10 ? 10 : $pagesize;
  30.             $this->offset    = ($this->page - 1) * $this->pagesize;
  31.             $this->params    = $params;
  32.             $this->pagerange = 10;
  33.         }
  34.       
  35.         function loadpage($sql)
  36.         {
  37.             $sql            = preg_replace("/select/i","select",$sql);
  38.             $sqlitems       = explode("select",$sql);
  39.             unset($sqlitems[0]);
  40.             $newsql         = implode("SELECT",$sqlitems);
  41.             $newsql         = "SELECT SQL_CALC_FOUND_ROWS ".$newsql." LIMIT {$this->offset},{$this->pagesize}";
  42.             $rs             = $this->E($newsql);
  43.             $pagesql        = "SELECT FOUND_ROWS() AS `allnum`";
  44.             $pagers         = $this->E($pagesql);
  45.             $pageresult     = $pagers->fields;
  46.           
  47.             $this->totalnum = $pageresult["allnum"];
  48.             $this->setpage();
  49.           
  50.             $offset         = $this->offset;
  51.             while(!$rs->EOF){
  52.                 $offset++;
  53.                 $rs->fields['offset'] = $offset;
  54.                 $this->results[]      = $rs->fields;
  55.                 $rs->MoveNext();  
  56.             }
  57.         }
  58.       
  59.         function setpage()
  60.         {
  61.             if(count($this->params) > 0){
  62.                 foreach($this->params as $key => $value){
  63.                     $params.= "{$key}={$value}&";
  64.                 }
  65.             }
  66.           
  67.             $this->totalpage = ceil($this->totalnum/$this->pagesize);
  68.           
  69.             $this->pagelink = "<span class='nolink'>".$this->page."/".$this->totalpage."</span>";
  70.           
  71.             //FIRST PREV
  72.             if($this->page > 1){
  73.                 $this->pagelink.= " <a href='?{$params}page=1'>FIRST</a> ";
  74.                 $this->pagelink.= " <a href='?{$params}page=".($this->page - 1)."'>PREV</a> ";
  75.             }else{
  76.                 $this->pagelink.= " <span class='nolink'>FIRST</span> ";
  77.                 $this->pagelink.= " <span class='nolink'>PREV</span> ";
  78.             }
  79.           
  80.             for($i = $this->page - $this->pagerange; $i <= $this->page + $this->pagerange; $i++){
  81.                 if($i < 1 || $i > $this->totalpage) continue;
  82.                 $this->pagelink.= $i == $this->page ? " <span class='currentpage'>[{$i}]</span> " : "<a href='?{$params}page={$i}'>[{$i}]</a> ";
  83.             }
  84.           
  85.             //NEXT LAST
  86.             if($this->page < $this->totalpage){
  87.                 $this->pagelink.= " <a href='?{$params}page=".($this->page + 1)."'>NEXT</a> ";
  88.                 $this->pagelink.= " <a href='?{$params}page={$this->totalpage}'>LAST</a> ";
  89.             }else{
  90.                 $this->pagelink.= " <span class='nolink'>NEXT</span> ";
  91.                 $this->pagelink.= " <span class='nolink'>LAST</span> ";
  92.             }
  93.         }
  94.     }


使用举例:
下载: list.php
  1. <?php
  2.     //引入ADODB
  3.     require_once dirname(__FILE__)."/../lib/adodb/adodb.inc.php";
  4.   
  5.     //DB configuration
  6.     $db_config = array("db_host"=>"localhost","db_user"=>"root","db_password"=>"123456","db_name"=>"flow");
  7.   
  8.     $page    = intval($_REQUEST['page']);
  9.     $sql     = "SELECT * FROM `flow_bulletins` WHERE 1=1 ";
  10.     $keyword != "" && $sql.= " AND (`bulletin_title_en` LIKE '%{$keyword}%' OR `bulletin_title_cn` LIKE '%{$keyword}%' OR `bulletin_title_fr` LIKE '%{$keyword}%') ";
  11.     $status  != "" && $sql.= " AND `enabled`='{$status}' ";
  12.     $sql    .= " ORDER BY `ordering`";
  13.     $pageparams = compact("keyword","status");
  14.     $pageobj = new pageclass($page, $pageparams);
  15.     $pageobj->loadpage($sql);
  16.     var_dump($pageobj);
  17. ?>
标签: php 分页

php 生成 xml 添加 BOM

前两天做公司网站的CMS,因为xml的问题郁闷了好几天,明明是utf-8的xml,可是前台的flash却总是在读取中文xml时出现乱码。
找了几天原来要在写xml文件时添加BOM信息。代码如下:

下载: adddom.php
  1. <?php
  2. $bom = pack("C3",239,187,191);
  3. $xml = $bom;
  4. ...
  5. $xml.= "...";
  6. file_put_contents($filename,$xml);
  7. ?>
标签: php BOM

php 生成缩略图

  1. <?php
  2.     /*
  3.      *  Create Thumbnail picture
  4.      *  Author: Liubing
  5.      *  Last Modify: 2010-05-06 12:09
  6.      *
  7.      *  How to use it:
  8.      *
  9.      *    $source_pic = dirname(__FILE__).'/1920VectorLove008.png';
  10.      *    $thumb = new Thumbnail($source_pic,250,100);
  11.      *    $thumb->create();
  12.      */
  13.     class Thumbnail
  14.     {
  15.         /* source picture */
  16.         var $source_pic;
  17.       
  18.         /* source picture width */
  19.         var $source_w;
  20.       
  21.         /* source picture height */
  22.         var $source_h;
  23.       
  24.         /* source picture mimetype */
  25.         var $source_mime;
  26.       
  27.         /* source picture is valid or not */
  28.         var $source_valid;
  29.       
  30.         /* thumb picture directory */
  31.         var $dest_dir;
  32.       
  33.         /* thumb picture name */
  34.         var $dest_pic;
  35.       
  36.         /* thumb picture width */
  37.         var $dest_w;
  38.       
  39.         /* thumb picture height */
  40.         var $dest_h;
  41.       
  42.         /* assign mimetype to function name */
  43.         var $mime2func;
  44.       
  45.         function Thumbnail($source_pic,$width="400",$height="300",$dest_dir="")
  46.         {
  47.             $this->source_pic   = $source_pic;
  48.             $this->source_valid = false;
  49.             $this->dest_dir     = $dest_dir == "" ? dirname(__FILE__) : $dest_dir;
  50.             $this->dest_w       = intval($width);
  51.             $this->dest_h       = intval($height);
  52.             $this->mime2func    = array("image/jpeg" => "jpeg", "image/gif" => "gif", "image/png" => "png");
  53.             $this->readSource();
  54.         }
  55.       
  56.         /* Read Source Picture */
  57.         function readSource()
  58.         {
  59.             if(file_exists($this->source_pic)){
  60.                 $picinfo = getimagesize($this->source_pic);
  61.                 if(is_array($picinfo)){
  62.                     $this->source_w     = $picinfo[0];
  63.                     $this->source_h     = $picinfo[1];
  64.                     $this->source_mime  = $picinfo['mime'];
  65.                     $this->source_valid = true;
  66.                   
  67.                     $basename           = basename($this->source_pic);
  68.                     $this->dest_pic     = substr(md5(rand()),0,10)."_".$this->dest_w."_".$this->dest_h."_".$basename;
  69.                   
  70.                     $this->setRealSize();
  71.                 }
  72.             }
  73.         }
  74.       
  75.         //Set Thumb Size (keep proportion)
  76.         function setRealSize()
  77.         {
  78.             if(!$this->source_valid) return;
  79.             if($this->dest_w < 1 || $this->dest_w >= $this->source_w) $this->dest_w = 0;
  80.             if($this->dest_h < 1 || $this->dest_h >= $this->source_h) $this->dest_h = 0;
  81.             if($this->dest_w == 0 && $this->dest_h == 0) return;
  82.           
  83.             if($this->dest_w > 0 && $this->dest_h > 0){
  84.                 if(($this->source_w / $this->dest_w) > ($this->source_h / $this->dest_h)){
  85.                     $this->dest_h = ceil(($this->source_h * $this->dest_w) / $this->source_w);
  86.                 }else{
  87.                     $this->dest_w = ceil(($this->source_w * $this->dest_h) / $this->source_h);
  88.                 }
  89.             }elseif($this->dest_w > 0){
  90.                 $this->dest_h = ceil(($this->source_h * $this->dest_w) / $this->source_w);
  91.             }else{
  92.                 $this->dest_w = ceil(($this->source_w * $this->dest_h) / $this->source_h);
  93.             }
  94.         }
  95.       
  96.         function create()
  97.         {
  98.             if(!$this->source_valid || $this->mime2func[$this->source_mime] == '') return;
  99.           
  100.             //create folder
  101.             if(substr($this->dest_dir,-1,1) != "/") $this->dest_dir .= "/";
  102.             $this->dest_dir .= "thumb/".date("Y-m");
  103.             if(!is_dir($this->dest_dir)) mkdir($this->dest_dir);
  104.           
  105.             //copy source to thumb
  106.             if($this->dest_w == 0 || $this->dest_h == 0){
  107.                 copy($this->source_pic,$this->dest_dir."/".$this->dest_pic);
  108.                 return;
  109.             }
  110.           
  111.             //create thumb
  112.             $createfunc = "imagecreatefrom".$this->mime2func[$this->source_mime];
  113.             $outputfunc = "image".$this->mime2func[$this->source_mime];
  114.             $d_im = imagecreatetruecolor($this->dest_w,$this->dest_h);
  115.             $s_im = $createfunc($this->source_pic);
  116.             imagecopyresized($d_im, $s_im, 0, 0, 0, 0, $this->dest_w, $this->dest_h, $this->source_w, $this->source_h);
  117.           
  118.             //save
  119.             $outputfunc($d_im,$this->dest_dir."/".$this->dest_pic);
  120.           
  121.             //destroy
  122.             imagedestroy($d_im);
  123.             imagedestroy($s_im);
  124.         }
  125.   
  126.     }
  127. ?>
标签: php 缩略图

Ubuntu/CentOS 安装 Memcache

平台: Ubuntu 9.10 + Nginx 0.7.65 + Mysql 5.1.45 + php 5.2.10 FastCGI

1. 下载memcache: http://memcached.googlecode.com/files/memcached-1.4.5.tar.gz

2. 解压安装
$ tar -zxvf memcached-1.4.5.tar.gz
$ cd memcached-1.4.5
$ ./configure
$ make
$ sudo make install


3. 启动
$ sudo /usr/local/bin/memcached -d -c 128 -u root -P /tmp/memcached.pid

4. 安装php-memcache扩展
下载:http://pecl.php.net/get/memcache-2.2.4.tgz

#解压安装
$ tar -zxvf memcache-2.2.4.tgz
$ cd memcache-2.2.4
$ /usr/local/php/bin/phpize
$ ./configure --with-php-config=/usr/local/php/bin/php-config --enable-memcache
$ make
$ sudo mkdir /usr/local/php/extensions/
$ sudo cp modules/memcache.so /usr/local/php/extensions/


#在php.ini中加入扩展
[vi /usr/local/php/etc/php.ini]
extension_dir = "/usr/local/php/extensions/"
extension     = "memcache.so"


重新启动php-fpm
$ sudo /usr/local/php/sbin/php-fpm restart

5. 测试

下载: memcache.php
  1. <?php
  2.     $mc = new Memcache;
  3.     $mc->connect("127.0.0.1",11211);
  4.     $item = $mc->get('item');
  5.     if(!is_array($item)){
  6.         echo "Add item to memcache";
  7.         $mc->add('item',array('item'));
  8.     }
  9.     $item = $mc->get('item');
  10.     var_dump($item);
  11. ?>

多刷新几次浏览器,我们会发现,只有第一次出现了Add item to memcache。

文档请参阅:http://php.net/manual/en/book.memcache.php

CentOS下按此步骤安装测试无误。