编程语言
首页 > 编程语言> > PHP如何实现类似java中hashset,hashmap

PHP如何实现类似java中hashset,hashmap

作者:互联网

php常用的数据类型 数组是只能以整型或字符串类型作为key,value可以是任意类型的数据,但是如何在php里面使用类似java中的hashset、hashmap结构或python中的字典dict,set结构,来存储以对象等其他非字符串整型为key的数据;这就要用到php的扩展spl,里面有个SplObjectStorage,它可以存储任意类型的key;
如下实现hashset集合

  <?php
// As an object set
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;

$s->attach($o1);
$s->attach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));

$s->detach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));
?> 

如下实现hashmap类型

// As a map from objects to data
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;

$s[$o1] = "data for object 1";
$s[$o2] = array(1,2,3);
if (isset($s[$o2])) {
    var_dump($s[$o2]);
}

标签:java,hashmap,dump,hashset,contains,var,new,o2,o1
来源: https://blog.csdn.net/weixin_39179620/article/details/123593205