Reference PHP array by multiple indexes

前端 未结 4 849
暗喜
暗喜 2021-01-04 21:47

This may be some sort of weird longer shortcut, and please correct me if I\'m mistaken in this train of thought...

I have a matrix of data that looks like:

4条回答
  •  滥情空心
    2021-01-04 22:27

    Surely an object would be the easy way?

    class Item {
        public $unique_url;
        public $url;
        public $other_data;
    
        public function __construct($unique_url, $url, $other_data)
        {
            $this->unique_url = $unique_url;
            $this->url = $url;
            $this->other_data = $other_data;
        }
    }
    
    
    
    class ItemArray {
        private $items = array();
    
        public function __construct()
        {
        }
    
        public function push(Item $item)
        {
            array_push($items, $item); //These may need to be reversed
        }
    
        public function getByURL($url)
        {
            foreach($items as $item)
            {
                if($item->url = $url)
                {
                    return $item;
                }
            }
        }
    
        public function getByUniqueURL($url)
        {
            foreach($items as $item)
            {
                if($item->unique_url = $unique_url)
                {
                    return $item;
                }
            }
        }
    
    }
    

    Then use it with

    $itemArray = new ItemArray();
    $item = new Item("someURL", "someUniqueURL","some other crap");
    $itemArray->push($item);
    
    $retrievedItem = $itemArray->getItemByURL("someURL");
    

    This technique has a little extra overhead due to object creation, but unless you're doing insane numbers of rows it would be fine.

提交回复
热议问题