php树形结构数据存取实例类

使用说明:

PHP常用类库

 代码如下

//载入函式
include_once(‘phpCodeZip.php’);
//建立加密文件(sourceDir要加密的php文件目录,targetDir加密后的文件目录)
$encryption = new PhoCodeZip(‘sourceDir’,’targetDir’);
//执行行加密
$encryption->zip();

数组类
class libArray
{
    /**
     * 多维数组合并
     * @return array
     */
    public static function merge ()
    {
        $args = func_get_args();
        $array = [];
        foreach ( $args as
$arg ) {
            if ( is_array($arg) ) {
                foreach ( $arg as $k => $v ) {
                    if ( is_array($v) ) {
                        $array[$k] = isset($array[$k]) ?
$array[$k] : [];
                        $array[$k] = self::merge($array[$k], $v);
                    } else {
                        $array[$k] = $v;
                    }
                }
            }
        }
        return $array;
    }

<?php
/**
 * Tanphp framework
 *
 *
 * @category   Tanphp
 * @package    Data_structure
 * @copyright  Copyright (c) 2012 谭博  tanbo.name
 * @version    $Id: Tree.php 25024 2012-11-26 22:22:22 tanbo $
 */

phpCodeZip.php源码下载
phpCodeZip.rar
phpCodeZip.php源码内容

    /**
     * 多维to一维
     * [1=>[‘a’=>’v1’]] to [‘1|a’=>’v1’]
     * @param array $array
     * @param string $delimiter
     * @param string $key
     * @return array
     */
    public static function mTo1 (array $array, $delimiter = ‘|’, $key =
”)
    {
        $data = [];
        if ( !is_array($array) ) {
            return $data;
        }
        foreach ( $array as $k => $v ) {
            $keyNew = trim($key.$delimiter.$k, $delimiter);
            if ( is_array($v) ) {
                $data = array_merge($data, self::mTo1($v, $delimiter,
$keyNew));
            } else {
                $data[$keyNew] = $v;
            }
        }
        return $data;
    }

/**
 * 树形结构数据存取类
 *
 * 用于对树形结构数据进行快速的存取
 *
 * @param array $arr
参数必须为标准的二维数组,包含索引字段(id)与表示树形结构的字段(path),如example中所示
 *
 * @example <code>
 * $arr = array(
 *  array( ‘id’ => 1, ‘name’ => ‘php’, ‘path’ => ‘1’ ),
 *  array( ‘id’ => 3, ‘name’ => ‘php1’, ‘path’ => ‘1-3’ ),
 *  array( ‘id’ => 2, ‘name’ => ‘mysql’, ‘path’ => ‘2’ ),
 *  array( ‘id’ => 6, ‘name’ => ‘mysql1’, ‘path’ => ‘2-6’ ),
 *  array( ‘id’ => 7, ‘name’ => ‘mysql2’, ‘path’ => ‘2-7’ ),
 *  array( ‘id’ => 5, ‘name’ => ‘php11’, ‘path’ => ‘1-3-5’
),
 *  array( ‘id’ => 4, ‘name’ => ‘php2’, ‘path’ => ‘1-4’ ),
 *   );
 *  $cate = new Tree($arr);
 * 
 *  $data = $cate->getChild(2);
 * 
 *  print_r($data->toArray());
 * </code>
 *
 */

复制代码 代码如下:

    /**
     * 数组排序
     * @param array $array
     * @param $column
     * @param bool $reverse
     * @return bool
     */
    public static function sort (array &$array, $column, $reverse =
FALSE)
    {
        $arrColumn = [];
        foreach ( $array as $key => $val ) {
            $arrColumn[$key] = $val[$column];
        }
        return array_multisort($arrColumn, $reverse ? SORT_DESC :
SORT_ASC, $array);
    }

class Tree
{
    public  $_info;                             //节点信息
    public  $_child = array();                  //子节点
    private $_parent;                           //父节点
    private $_data;                             //当前操作的临时数据
    private static $_indexs         = array();  //所有节点的索引
    private static $_index_key      = ‘id’;     //索引键
    private static $_tree_key       = ‘path’;   //树形结构表达键
    private static $_tree_delimiter = ‘-‘;      //属性结构表达分割符
   
   
   
    /**
     * 构造函数
     *
     * @param array $arr
     * @param boole $force_sort 如果为真,将会强制对$arr 进行排序
     * @return void
     */
    public function __construct(array $arr = array(), 
$force_sort=true)
    {
        if ($force_sort === true) {
            $arr=$this->_array_sort($arr, self::$_tree_key);
        }
        if (!empty($arr)) {
            $this->_init($arr);
        }
    }
   
    /**
     * 初始存储树形数据
     *
     * @param array $arr
     * @return void
     */
    private function _init(array $arr)
    {
        foreach ($arr as
$item) {
            $path        = $item[self::$_tree_key];
            $paths       =
explode(self::$_tree_delimiter,
$path);
            $count_paths = count($paths);
            $parent_id   = isset($paths[$count_paths-2]) ?
$paths[$count_paths-2] : NULL;
           
            if (   $count_paths>1                                  
//如果有父级
                && array_key_exists($parent_id, self::$_indexs)     
//父级已经被存入索引
                && self::$_indexs[$parent_id] instanceof Tree   
//父级为Tree对象
            ) {
                self::$_indexs[$parent_id]->addChild($item);
            } elseif ($count_paths == 1) {
                $this->addChild($item);
            } else {
                throw new Exception(“path数据错误”.var_export($item,
true));
            }
           
        }
       
        //print_r(self::$_indexs);
    }
   
    /**
     * 添加子节点
     *
     * @param array $item
     * @return void
     */
    public function addChild(array $item, $parent = NULL)
    {
        $child          = new Tree();
        $child->_info   = $item;
        $child->_parent = $parent == NULL ? $this : $parent;
        $child->_parent->_child[] =  $child;
       
        $this->_addIndex($item, $child->_getSelf());
    }
   
    /**
     * 添加节点到索引
     *
     * @param array $item
     * @param mix $value
     * @return void
     */
    private function _addIndex(array $item, $value)
    {
        if (array_key_exists(self::$_index_key, $item) &&
is_int($item[self::$_index_key])) {
            self::$_indexs[$item[self::$_index_key]] = $value;
        } else {
            throw new Exception(“id字段不存在或者不为字符串”);
        }
    }
   
   
    /**
     * 获取对自己的引用
     *
     * @return Tree object quote
     */
    private function _getSelf()
    {
        return $this;
    }
   
    /**
     * 获取指定id的节点的子节点
     *
     * @param int $id
     * @return Tree object
     */
    public function getChild($id)
    {
        $data       = self::$_indexs[$id]->_child;
        $this->_data = $data;
        return $this;
    }
   
    /**
     * 获取指定id的节点的父节点
     *
     * @param int $id
     * @return Tree object
     */
    public function getParent($id)
    {
        $data = self::$_indexs[$id]->_parent;
        $this->_data = $data;
        return $this;
    }
   
    /**
     * 获取指定id的节点的同级节点
     *
     * @param int $id
     * @return Tree object
     */
    public function getBrother($id)
    {
        $data = self::$_indexs[$id]->_parent->_child;
        $this->_data = $data;
        return $this;
    }
   
    /**
     * 将Tree对象转化为数组
     *
     * @param  object $object
     * @return array
     */
     public function toArray($obj = NULL)
     {
        $obj  = ($obj === NULL) ? $this->_data : $obj;
        $arr  = array();
        $_arr = is_object($obj) ? $this->_getBaseInfo($obj) :
$obj;
       
        if (is_array($_arr)) {
            foreach ($_arr as $key => $val){
               
                $val = (is_array($val) || is_object($val)) ?
$this->toArray($val) : $val;
                   
                $arr[$key] = $val;
            }
        } else {
            throw new Exception(“_arr不是数组”);
        }
       
    
        return $arr;
    }
   
    /**
     * 过滤_parent等字段,以免造成无限循环
     *
     * @param object $obj
     * @return void
     */
    private function _getBaseInfo($obj)
    {
        $vars = get_object_vars($obj);
        $baseInfo[‘_info’]  =  $vars[‘_info’];
        $baseInfo[‘_child’] =  $vars[‘_child’];
        return $baseInfo;
    }
   
    /**
     * 二维数组排序
     *
     * 根据指定的键名对二维数组进行升序或者降序排列
     *
     * @param array  $arr 二维数组
     * @param string $keys
     * @param string $type 必须为 asc或desc
     * @throws 当参数非法时抛出异常
     * @return 返回排序好的数组
     */
    private function _array_sort(array $arr, $keys, $type = ‘asc’) {
        if (!is_string($keys)) {
            throw new
Exception(“非法参数keys:参数keys的类型必须为字符串”);
        }
   
        $keysvalue = $new_array = array();
        foreach ($arr as $k=>$v) {
            if (!is_array($v) || !isset($v[$keys])) {
                throw new
Exception(“参数arr不是二维数组或arr子元素中不存在键'{$keys}'”);
            }
            $keysvalue[$k] = $v[$keys];
        }
   
        switch ($type) {
            case ‘asc’:
                asort($keysvalue);
                break;
            case ‘desc’:
                arsort($keysvalue);
                break;
            default:
                throw new Exception(“非法参数type :参数type的值必须为
‘asc’ 或 ‘desc'”);
        }
   
        reset($keysvalue);
        foreach ($keysvalue as $k=>$v) {
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }
   
}

/*
* @license:MIT & GPL
*/
class PhpCodeZip{
//欲進行壓縮加密的來源資料夾
var $sourceDir = ‘.’;
//進行壓縮加密的存放的資料夾
var $targetDir = ‘tmp’;
//是否進行加密
var $bcompiler = true;
//是否去除空白註解斷行
var $strip = true;
//來源資料夾檔案路徑陣列
var $sourcefilePaths = array();
//目的資料夾檔案路徑陣列
var $targetPaths = array();
//進行壓縮加密前的資料夾大小
var $sizeBeforeZip = null;
//進行壓縮加密後的資料夾大小
var $sizeAfterZip = null;
//斷行的輸出
var $newline = ”;
/**
* 建構子
*
* @param string $sourceDir 來源資料夾
* @param string $targetDir 目的資料夾
* @param boolean $bcompiler 是否進行加密
* @param boolean $strip 是否去除空白註解斷行
* @return boolean
*/
public function
PhpCodeZip($sourceDir=’.’,$targetDir=’tmp’,$bcompiler=true,$strip=true){
//配置初始變數
$this->sourceDir = $sourceDir;
$this->targetDir = $targetDir;
$this->bcompiler = $bcompiler;
//檢查來源資料是否存在

    /**
     * 添加索引
     * @param array $array
     * @param $key
     * @return array
     */
    public static function index (array $array, $key)
    {
        $ret = [];
        foreach ( $array as $val ) {
            $ret[$val[$key]] = $val;
        }
        return $ret;
    }

?>

if(!is_dir($this->sourceDir)){
die(‘指定的來源資料夾’.$this->sourceDir.’不存在,請重新設定’);
} else {
//如果指定的目的資料夾存在,砍掉重練
if(is_dir($this->targetDir)){
echo ‘【初始化目的地資料夾】’.$this->newline.$this->newline;
$this->cleanDir($this->targetDir,true);
}
//建立與來源資料夾結構一樣的目的資料夾
mkdir($this->targetDir,0777);
$dir_paths =
$this->getPaths($this->sourceDir,’*’,GLOB_ONLYDIR);
foreach($dir_paths as $key => $path){
$path = explode(‘/’,$path);
$path[0] = $this->targetDir;
echo ‘=> ‘.join(‘/’,$path).$this->newline;
mkdir(join(‘/’,$path),0777);
}
//取得來源資料夾的檔案路徑清單
$this->sourcefilePaths =
$this->getPaths($this->sourceDir,’*’);
//配對應目的地的檔案路徑清單
foreach($this->sourcefilePaths as $key => $path){
//設定目的資料夾檔案路徑
$path = explode(‘/’,$path);
$path[0] = $this->targetDir;
$this->targetPaths[$key] = join(‘/’,$path);
}
//記錄執行前的資料夾大小
$this->sizeBeforeZip =
$this->getSizeUnit($this->getDirSize($this->sourceDir),2);
echo $this->newline.$this->newline;
}
}
/**
* 進行壓縮加密
* @return boolean
*/
public function zip(){
$this->newline = ”;
echo
‘【開始進行加密程序】(資料夾大小:’.$this->sizeBeforeZip.’)’.$this->newline.$this->newline;
//將來源檔案進行壓縮
foreach($this->sourcefilePaths as $key => $path){
if(is_file($path)){
//取得檔案資訊
$pathInfo = pathInfo($path);
echo ‘讀取來源檔:’.$path.$this->newline;
//取得壓縮後的內容
echo ‘=>去除空白註解……….’;
if($this->strip && $pathInfo[‘extension’] == ‘php’){
$fileAterZip = php_strip_whitespace($path);
} else {
$fileAterZip = file_get_contents($path);
}
echo ‘完畢’.$this->newline;

    /**
     * 添加前后缀
     * @param $array
     * @param null $pre
     * @param null $suf
     * @return array
     */
    public static function addFix (array $array, $pre = NULL, $suf =
NULL)
    {
        $ret = [];
        foreach ( $array as $key => $val ) {
            $ret[$key] = $pre.$val.$suf;
        }
        return $ret;
金沙js333娱乐场,    }
}

//取壓縮後的內容寫到目的位置
$fp = fopen($this->targetPaths[$key],’w+’);
echo ‘=>寫入目的檔……….’;
fwrite($fp,$fileAterZip);
fclose($fp);
echo ‘完畢’.$this->newline;
//是否若選擇進行加密
if($this->bcompiler && $pathInfo[‘extension’] == ‘php’){
echo ‘=>加密原始檔……….’;
//複製原始檔
$fh = fopen($this->targetPaths[$key].’encrypt.php’, “w”);
bcompiler_write_header($fh);
bcompiler_write_file($fh, $this->targetPaths[$key]);
bcompiler_write_footer($fh);
fclose($fh);
//刪除未加密的原始檔

数据检查类
class libCheck
{
    /**
     * 是否为IP(IPv4)
     * @param $ip
     * @return bool
     */
    public static function isIP ($ip)
    {
        $isIP = filter_var($ip, FILTER_VALIDATE_IP) ? TRUE : FALSE;
        return $isIP;
    }

unlink($this->targetPaths[$key]);
//重新命名加密過後的檔案

    /**
     * 是否为邮箱地址
     * @param $mail
     * @return bool
     */
    public static function isMail ($mail)
    {
        $isMail = filter_var($mail, FILTER_VALIDATE_EMAIL) ? TRUE :
FALSE;
        return $isMail;
    }

rename($this->targetPaths[$key].’encrypt.php’,$this->targetPaths[$key]);
echo ‘完畢’.$this->newline;
}
echo $this->newline.$this->newline;
}
}
//重新計算壓縮加密後的資料夾大小
$this->sizeAfterZip =
$this->getSizeUnit($this->getDirSize($this->targetDir),2);
echo ‘【結束加密程序】’.$this->newline.$this->newline;

    /**
     * 是否为URL
     * @param $url
     * @return bool
     */
    public static function isURL ($url)
    {
        $isMail = filter_var($url, FILTER_VALIDATE_URL) ? TRUE :
FALSE;
        return $isMail;
    }

echo ‘《報告資訊》’.$this->newline;
echo
‘來源資料夾:’.$this->sourceDir.'(‘.$this->sizeBeforeZip.’)’.$this->newline;
echo
‘目的資料夾:’.$this->targetDir.'(‘.$this->sizeAfterZip.’)’.$this->newline;
echo
‘檔案大小增幅:+’.$this->getSizeUnit(($this->getDirSize($this->targetDir)

    /**
     * 是否为正整数
     * @param $num
     * @return bool
     */
    public static function isPosiInt ($num)
    {
        $isPosiInt = is_int($num) && $num > 0;
        return $isPosiInt;
    }

  • $this->getDirSize($this->sourceDir))).$this->newline;
    echo
    ‘檔案總數:’.count($this->sourcefilePaths).’個’.$this->newline;

    /**
     * 是否在范围内
     * @param $num
     * @param int $min
     * @param null $max
     * @return bool
     */
    public static function isBetween ($num, $min = 0, $max = NULL)
    {
        $isBetween = $num >= $min;
        if ( $max ) {
            $isBetween = $isBetween && $num <= $max;
        }
        return $isBetween;
    }

}
/**
* 刪除目錄夾所有檔案
*
* @param string $dir 欲刪除的資料夾
* @param boolean $deleteSelf 同時刪除資料夾
* @return void
*/
private function cleanDir($dir=’.’,$deleteSelf=true){
if(!$dh = @opendir($dir)) return;
while (($obj = readdir($dh))) {
if($obj==’.’ || $obj==’..’) continue;
if (!@unlink($dir.’/’.$obj)) $this->cleanDir($dir.’/’.$obj, true);
}
if ($deleteSelf){
closedir($dh);
@rmdir($dir);
}
}
/**
* 取得資料夾的總檔案大小
*
* @param string $dir 欲剖析的資料夾
* @return int 位元組
*/
private function getDirSize($dir=’.’){
//取得檔案路徑清單
$filePaths = $this->getPaths($dir,’*’);
//初始化計數器
$sizeCounter = 0;
foreach($filePaths as $key => $path){
$sizeCounter = $sizeCounter + filesize($path);
}
return ($sizeCounter);
}
/**
* 取得資料夾所有配對的路徑
*
* @param string $start_dir 欲剖析的資料夾
* @return array 檔案路徑陣列
*/
private function getPaths($sDir, $sPattern, $nFlags = NULL){
$sDir = escapeshellcmd($sDir);
$aFiles = glob(“$sDir/$sPattern”, $nFlags);
foreach (glob(“$sDir/*”, GLOB_ONLYDIR) as $sSubDir) {
$aSubFiles = $this->getPaths($sSubDir, $sPattern, $nFlags);
$aFiles = array_merge($aFiles, $aSubFiles);
}
return $aFiles;
}
/**
* 檔案大小單位轉換函式
*
* @param int 檔案大小
* @param int 小數點位數
* @param boolean 是否要將資料切成陣列
* @return mix 字串或陣列
*/
public function getSizeUnit($size,$decimal=2,$split=false){
//設定單位序列
$unit = array(‘Bytes’,’KB’,’MB’,’GB’,’TB’,’PB’,’EB’,’ZB’,’YB’);
//初始化索引
$flag = 0;
//進行簡化除算
while($size >= 1024){
$size = $size / 1024;
$flag++;
}
//是否要將數值與單位分開
if($split){
$sizeUnit = array(
‘size’ => number_format($size,$decimal),
‘unit’ => $unit[$flag]
);
} else {
$sizeUnit = (number_format($size,$decimal)).$unit[$flag];
}
//回傳大小與單位
return ($sizeUnit);
}
}

    /**
     * 是否为有效长度
     * @param $str
     * @param int $min
     * @param null $max
     * @return bool
     */
    public static function isValidLen ($str, $min = 1, $max = NULL)
    {
        $length = mb_strlen($str);
        $isValidLen = self::isBetween($length, $min, $max);
        return $isValidLen;
    }
}

您可能感兴趣的文章:

  • php生成PDF格式文件并且加密
  • PHP实现加密文本文件并限制特定页面的存取的效果

文件类

发表评论

电子邮件地址不会被公开。 必填项已用*标注