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

 更新时间:2016年11月25日 17:28  点击:2015
本文章来给大家分享一款不错的树形结构的php类代码,各位朋友可参考。
 代码如下 复制代码


<?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 $
 */


/**
 * 树形结构数据存取类
 *
 * 用于对树形结构数据进行快速的存取
 *
 * @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>
 *
 */

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;
    }
   
}

?>

在php中地址验证写法各种各样的,下面我来总结几种常用的email地址验证实例,最简单的是直接使用正则表达式preg_match(\"/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*@([a-z0-9\\-]+\\.)+[a-z]{2,6}$/ix来验证了。

CodeIgniter框架邮件地址验证

 代码如下 复制代码

/**
     * Valid Email
     *
     * @access  public
     * @param   string
     * @return  bool
     */
    function valid_email($str)
    {
        return ( ! preg_match("/^([a-z0-9+_-]+)(.[a-z0-9+_-]+)*@([a-z0-9-]+.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
    }

PHPCMS邮件正则验证

 代码如下 复制代码

/**
 * 判断email格式是否正确
 * @param $email
 */
function is_email($email) {
    return strlen($email) > 6 && preg_match("/^[w-.]+@[w-.]+(.w+)+$/", $email);
}

WordPress邮件地址验证函数

 代码如下 复制代码

/**
 * Verifies that an email is valid.
 *
 * Does not grok i18n domains. Not RFC compliant.
 *
 * @since 0.71
 *
 * @param string $email Email address to verify.
 * @param boolean $deprecated Deprecated.
 * @return string|bool Either false or the valid email address.
 */
function is_email( $email, $deprecated = false ) {
    if ( ! empty( $deprecated ) )
        _deprecated_argument( __FUNCTION__, '3.0' );
 
    // Test for the minimum length the email can be
    if ( strlen( $email ) < 3 ) {
        return apply_filters( 'is_email', false, $email, 'email_too_short' );
    }
 
    // Test for an @ character after the first position
    if ( strpos( $email, '@', 1 ) === false ) {
        return apply_filters( 'is_email', false, $email, 'email_no_at' );
    }
 
    // Split out the local and domain parts
    list( $local, $domain ) = explode( '@', $email, 2 );
 
    // LOCAL PART
    // Test for invalid characters
    if ( !preg_match( '/^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$/', $local ) ) {
        return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
    }
 
    // DOMAIN PART
    // Test for sequences of periods
    if ( preg_match( '/.{2,}/', $domain ) ) {
        return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
    }
 
    // Test for leading and trailing periods and whitespace
    if ( trim( $domain, " tnrx0B." ) !== $domain ) {
        return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
    }
 
    // Split the domain into subs
    $subs = explode( '.', $domain );
 
    // Assume the domain will have at least two subs
    if ( 2 > count( $subs ) ) {
        return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
    }
 
    // Loop through each sub
    foreach ( $subs as $sub ) {
        // Test for leading and trailing hyphens and whitespace
        if ( trim( $sub, " tnrx0B-" ) !== $sub ) {
            return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
        }
 
        // Test for invalid characters
        if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
            return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
        }
    }
 
    // Congratulations your email made it!
    return apply_filters( 'is_email', $email, $email, null );
}


例 自己写的

 

 代码如下 复制代码
$email = "tanklo_--vehy@yahoo.com.cn";
    function check_email($email) {
       $pattern_test = "/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
       return  preg_match($pattern_test,$email);
    }
echo check_email($email);
在php开发中我们经常会面要提供预定义判断变量或常量或函数是不是有了,下面我来介绍一些常用的判断常量、变量和函数是否存在应用实例。


常量检测使用defined,定义常量则是define。注意待检测的常量需要使用引号(单双均可),如:

 代码如下 复制代码

if (defined('CONST_NAME')) {
    //do something 
}

变量检测则是使用isset,注意变量未声明或声明时赋值为NULL,isset均返回FALSE,如:

 代码如下 复制代码

if (isset($var_name)) {
    //do something
}

函数检测用function_exists,注意待检测的函数名也需要使用引号,如:

if (function_exists('fun_name')) {
 fun_name();
}

先不说多了我们看一个实例

 代码如下 复制代码


<?php
/* 判断常量是否存在*/
if (defined('MYCONSTANT')) {
echo MYCONSTANT;
}
//判断变量是否存在
if (isset($myvar)) {
echo "存在变量$myvar.";
}
//判断函数是否存在
if (function_exists('imap_open')) {
echo "存在函数imag_openn";
} else {
echo "函数imag_open不存在n";
}
?>


function_exists判断函数是否存在

 代码如下 复制代码
 
<?php
if (function_exists('test_func')) {
    echo "函数test_func存在";
} else {
    echo "函数test_func不存在";
}
?>

 

filter_has_var函数

filter_has_var() 函数检查是否存在指定输入类型的变量。

若成功,则返回 true,否则返回 false。

 

 代码如下 复制代码
<?php
if(!filter_has_var(INPUT_GET, "name"))
 {
 echo("Input type does not exist");
 }
else
 {
 echo("Input type exists");
 }
?>
 

输出为. Input type exists

本文章来给各位同学详细介绍关于php 计算两个日期这间的间隔天数实例,各位同学可参考,我们一般是把日期用strtotime转换,然后再进行算,这样可以精确到时分秒去哦。


例1

直接把日期转换

 代码如下 复制代码

function daysbetweendates($date1, $date2){
    $date1 = strtotime($date1);
    $date2 = strtotime($date2);
    $days = ceil(abs($date1 - $date2)/86400);
    return $days;
}

例2

 代码如下 复制代码

<?php
functionmaketime($date)
{
list($year,$month,$day) = explode('-',$date);
returnmktime(0,0,0,$month,$day,$year);
}
$date1 = '2007-01-08';
$date2 = '2007-03-01';
$d = (maketime($date2) - maketime($date1)) / (3600*24);
echo'相差$d 天';

?>


例3

PHP实现两个日期间隔的年、月、周、日数的计算

 

 代码如下 复制代码
<?php
    function format($a,$b){
        //检查两个日期大小,默认前小后大,如果前大后小则交换位置以保证前小后大
        if(strtotime($a)>strtotime($b)) list($a,$b)=array($b,$a);
        $start  = strtotime($a);
        $stop   = strtotime($b);
        $extend = ($stop-$start)/86400;
        $result['extends'] = $extend;
        if($extend<7){                //如果小于7天直接返回天数
            $result['daily'] = $extend;
        }elseif($extend<=31){        //小于28天则返回周数,由于闰年2月满足了
            if($stop==strtotime($a.'+1 month')){
                $result['monthly'] = 1;
            }else{
                $w = floor($extend/7);
                $d = ($stop-strtotime($a.'+'.$w.' week'))/86400;
                $result['weekly']  = $w;
                $result['daily']   = $d;
            }
        }else{
            $y=    floor($extend/365);
            if($y>=1){                //如果超过一年
                $start = strtotime($a.'+'.$y.'year');
                $a     = date('Y-m-d',$start);
                //判断是否真的已经有了一年了,如果没有的话就开减
                if($start>$stop){
                    $a = date('Y-m-d',strtotime($a.'-1 month'));
                    $m =11;
                    $y--;   
                }
                $extend = ($stop-strtotime($a))/86400;
            }
            if(isset($m)){
                $w = floor($extend/7);
                $d = $extend-$w*7;
            }else{
                $m = isset($m)?$m:round($extend/30);
                $stop>=strtotime($a.'+'.$m.'month')?$m:$m--;
                if($stop>=strtotime($a.'+'.$m.'month')){
                    $d=$w=($stop-strtotime($a.'+'.$m.'month'))/86400;
                    $w = floor($w/7);
                    $d = $d-$w*7;
                }
            }
            $result['yearly']  = $y;
            $result['monthly'] = $m;
            $result['weekly']  = $w;
            $result['daily']   = isset($d)?$d:null;
        }
        return array_filter($result);
    }
 
    print_r(format('2012-10-1','2012-12-15'));
?>
本文章来介绍根据用户出生年月来计算年龄/生肖/星座的各种程序实例代码,各位朋友不防进入参考


//计算年龄

 代码如下 复制代码
function birthday($mydate){
    $birth=$mydate;
    list($by,$bm,$bd)=explode('-',$birth);
    $cm=date('n');
    $cd=date('j');
    $age=date('Y')-$by-1;
    if ($cm>$bm || $cm==$bm && $cd>$bd) $age++;
    return $age;
//echo "生日:$birthn年龄:$agen";
}

根据年份计算生肖

 代码如下 复制代码

<?php
/**
 *  计算.生肖
 * 
 * @param int $year 年份
 * @return str
 */
function get_animal($year){
    $animals = array(
            '鼠', '牛', '虎', '兔', '龙', '蛇', 
            '马', '羊', '猴', '鸡', '狗', '猪'
    );
    $key = ($year - 1900) % 12;
    return $animals[$key];
}

echo get_animal(1990);    // 马
echo get_animal(2010);    // 虎

根据生日计算星座

 代码如下 复制代码


<?php
/**
 *  计算.星座
 *
 * @param int $month 月份
 * @param int $day 日期
 * @return str
 */
function get_constellation($month, $day){
    $signs = array(
            array('20'=>'宝瓶座'), array('19'=>'双鱼座'),
            array('21'=>'白羊座'), array('20'=>'金牛座'),
            array('21'=>'双子座'), array('22'=>'巨蟹座'),
            array('23'=>'狮子座'), array('23'=>'处女座'),
            array('23'=>'天秤座'), array('24'=>'天蝎座'),
            array('22'=>'射手座'), array('22'=>'摩羯座')
    );
    $key = (int)$month - 1;
    list($startSign, $signName) = each($signs[$key]);
    if( $day < $startSign ){
        $key = $month - 2 < 0 ? $month = 11 : $month -= 2;
        list($startSign, $signName) = each($signs[$key]);
    }
    return $signName;
}

echo get_constellation(12, 11);    // 射手座
echo get_constellation(6, 6);      // 双子座

[!--infotagslink--]

相关文章

  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • php简单数据操作的实例

    最基础的对数据的增加删除修改操作实例,菜鸟们收了吧...2013-09-26
  • 解决Mybatis 大数据量的批量insert问题

    这篇文章主要介绍了解决Mybatis 大数据量的批量insert问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-09
  • Antd-vue Table组件添加Click事件,实现点击某行数据教程

    这篇文章主要介绍了Antd-vue Table组件添加Click事件,实现点击某行数据教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-17
  • 详解如何清理redis集群的所有数据

    这篇文章主要介绍了详解如何清理redis集群的所有数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-18
  • vue 获取到数据但却渲染不到页面上的解决方法

    这篇文章主要介绍了vue 获取到数据但却渲染不到页面上的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-19
  • php把读取xml 文档并转换成json数据代码

    在php中解析xml文档用专门的函数domdocument来处理,把json在php中也有相关的处理函数,我们要把数据xml 数据存到一个数据再用json_encode直接换成json数据就OK了。...2016-11-25
  • mybatis-plus 处理大数据插入太慢的解决

    这篇文章主要介绍了mybatis-plus 处理大数据插入太慢的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-18
  • postgresql数据添加两个字段联合唯一的操作

    这篇文章主要介绍了postgresql数据添加两个字段联合唯一的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-04
  • Vue生命周期activated之返回上一页不重新请求数据操作

    这篇文章主要介绍了Vue生命周期activated之返回上一页不重新请求数据操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-07-26
  • c# socket网络编程接收发送数据示例代码

    这篇文章主要介绍了c# socket网络编程,server端接收,client端发送数据,大家参考使用吧...2020-06-25
  • vue 数据(data)赋值问题的解决方案

    这篇文章主要介绍了vue 数据(data)赋值问题的解决方案,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-29
  • 解决vue watch数据的方法被调用了两次的问题

    这篇文章主要介绍了解决vue watch数据的方法被调用了两次的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-07
  • Python3 常用数据标准化方法详解

    这篇文章主要介绍了Python3 常用数据标准化方法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-24
  • el-table树形表格表单验证(列表生成序号)

    这篇文章主要介绍了el-table树形表格表单验证(列表生成序号),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-01
  • js如何构造elementUI树状菜单的数据结构详解

    由于业务需要,要求实现树形菜单,且菜单数据由后台返回,下面这篇文章主要给大家介绍了关于js如何构造elementUI树状菜单的数据结构的相关资料,需要的朋友可以参考下...2021-05-13
  • node.js从数据库获取数据

    这篇文章主要为大家详细介绍了node.js从数据库获取数据的具体代码,nodejs可以获取具体某张数据表信息,感兴趣的朋友可以参考一下...2016-05-09
  • 分享MYSQL插入数据时忽略重复数据的方法

    使用下以两种方法时必须把字段设为”主键(PRIMARY KEY”或”唯一约束(UNIQUE)”。1:使用REPLACE INTO (此种方法是利用替换的方法,有点似类于先删除再插入) 复制代码 代码如下:REPLACE INTO Syntax REPLACE [LOW_PRIO...2013-10-04
  • PostgreSQL 恢复误删数据的操作

    这篇文章主要介绍了PostgreSQL 恢复误删数据的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-18
  • C#实现窗体间传递数据实例

    这篇文章主要介绍了C#实现窗体间传递数据实例,需要的朋友可以参考下...2020-06-25