2013-08-24 16 views
0

嗯,我想过在PHP中使用ArrayList,因为它在PHP中非常有用,并节省了大量时间。在PHP中使用哈希映射(通过键获取)和java一样?

我认为这会是很酷的PHP中,所以我做使PHP ArrayList类:

Class ArrayList 
{ 
    public $arrayList; 

    function __construct() 
    { 
     $this->arrayList = array(); 
    } 

    public function add($element) 
    { 
     $this->arrayList[] = $element; 
    } 

    public function remove($index) 
    { 
     if (is_numeric($index)) { 
      unset($this->arrayList[$index]); 
     } 
    } 

    public function get($index) 
    { 
     return $this->arrayList[$index]; 
    } 
} 

现在,我发现我需要一个hashmap的列表类型多,这样我就可以通过钥匙获取物品。 假设我需要获取mysql db名称,所以我只是做$data->hashmap->get("db_name")。 这将返回数据库名称值。

有没有办法做到这一点?

回答

4

PHP已经内置了你想要的是什么数据类型:

  • A “HashMap的” 是一个关联数组
  • 的 “ArrayList的” 仅仅是一个数组

例子:

$my_hash_map = array('x' => 5, 'y' => 10); 
$my_hash_map['x'] + $my_hash_map['y'] // => 15 

$my_array_list = array(); 
$my_array_list[] = 5; 
$my_array_list[0] // => 5 

请参阅Arrays在PHP文档中。

0

在PHP数组中可以有字符串键。你也可以使用stdClass