zoukankan      html  css  js  c++  java
  • PHP处理二维数组合并 时间复杂度O(n)

     一直没怎么写博客,感觉很多东西都遗忘, 在写ArrayAccess同时把时间复杂度温习下 ,这篇博客给大家说说关于PHP预定义接口中常用到的重量级人物: ArrayAccess。大家也许会问,最基本、最常用的预定义接口有6个呢,为啥非得说这个。从日常的使用情况来看:这个出现的频率非常高,特别是在框架中,比如Laravel、Slim等都会用到,并且用得非常经典,让人佩服啊。从技术上说:说实话其他的我用的少啊!只是知道简单的用法,对他的理解比较浅显,不敢在这里误导大家,哈哈!今天我要写的内容也不一定都正确,不对之处还请指正。

    ArrayAccess

      先说 ArrayAccess 吧!ArrayAccess 的作用是使得你的对象可以像数组一样可以被访问。应该说 ArrayAccess 在PHP5中才开始有的,PHP5中加入了很多新的特性,当然也使类的重载也加强了,PHP5 中添加了一系列接口,这些接口和实现的 Class 统称为 SPL。

    ArrayAccess 这个接口定义了4个必须要实现的方法:

    1 {
    2    abstract public offsetExists ($offset)  //检查偏移位置是否存在
    3    abstract public offsetGet ($offset)     //获取一个偏移位置的值
    4    abstract public offsetSet ($offset ,$value) //设置一个偏移位置的值
    5    abstract public offsetUnset ($offset)       //复位一个偏移位置的值
    6 }

    所以我们要使用ArrayAccess这个接口,就要实现相应的方法,

    复制代码
    class obj implements ArrayAccess
    {
    private $container;


    public function __construct($data)
    {
    $this->container = $data;
    }

    public function offsetExists($offset)
    {
    // TODO: Implement offsetExists() method.
    $arrKey = array_search($offset, array_column($this->container, 'bookId'));
    return $arrKey;

    }

    public function offsetSet($offset, $value)
    {
    $arrKey=$this->offsetExists($offset);
    if($arrKey!==false){
    // TODO: Implement offsetSet() method.
    $this->offsetUnset($arrKey);
    $this->container[$arrKey] = array_merge($this->container[$arrKey], $value);
    }
    }

    public function offsetGet($offset)
    {
    // TODO: Implement offsetGet() method.
    return $this->container;
    }

    public function offsetUnset($offset)
    {
    unset($this->container[$offset]['bookId']);
    // TODO: Implement offsetUnset() method.
    }

    }

    $bookBaseInfo = [
    ['bookId' => 1, 'name' => '程序员修炼之道'],
    ['bookId' => 2, 'name' => '择天记'],
    ['bookId' => 3, 'name' => 'PHP核心'],
    ];
    $bookUpdateTime = [
    ['bookId' => 3, 'timestamp' => 11],
    ['bookId' => 2, 'timestamp' => 22],
    ];
    $obj = new obj($bookBaseInfo);
    foreach ($bookUpdateTime as $key => $value) {
    $obj[$value['bookId']]=$value;
    }
    var_dump($obj['bookId']);die;
    复制代码

     这个示例里面只用一层循环 ,所以时间事件复杂度是O(n);

    
    
    人生是一道单行轨迹,留下怎样的风景,在于心灵的旅行
  • 相关阅读:
    STL map与Boost unordered_map
    static constructors in C++? need to initialize private static objects
    谈谈C++继承中的重载,覆盖和隐藏
    C++继承:公有,私有,保护
    C++ using关键字作用总结
    ++iter的效率比iter++的效率高
    C++中dynamic_cast,static_cast,const_cast,reinterpret_cast
    【转】WinForm中添加闪屏窗口的两种方法
    【转】一个不错的Matlab的gui界面设计实例 (20081003 15:47:30)matlab gui 界面 校园 分类:Matlab实例
    制作一个WinForm的闪屏
  • 原文地址:https://www.cnblogs.com/friendwrite/p/10335479.html
Copyright © 2011-2022 走看看