0

好吧,我曾想过在 PHP 中使用 ArrayList,因为它在 PHP 中非常有用,并且可以节省大量时间。

我认为使用 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];
    }
}

现在,我注意到我需要一个更多的列表类型 a hashmap,所以我可以按键获取项目。假设我需要获取 mysql 数据库名称,所以我会这样做$data->hashmap->get("db_name")。这将返回数据库名称值。

有没有办法做到这一点?

4

2 回答 2

4

PHP 具有内置的数据类型,可以满足您的需求:

  • “哈希图”是一个关联数组
  • “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

请参阅PHP 文档中的数组

于 2013-08-24T16:30:56.970 回答
0

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

于 2013-08-24T16:30:06.420 回答