PHP 中是否有 Java HashMap 等价物?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6841379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there Java HashMap equivalent in PHP?
提问by newbie
I need PHP object similar to HashMap in Java, but I didn't find when I googled, so if someone knows how I can mimic HashMaps in PHP, help would be appreciated.
我需要类似于 Java 中的 HashMap 的 PHP 对象,但是我在谷歌搜索时没有找到,所以如果有人知道我如何在 PHP 中模拟 HashMap,我们将不胜感激。
回答by sushil bharwani
Arrays in PHP can have Key Value structure.
PHP 中的数组可以具有键值结构。
回答by Boris Gordon
Depending on what you want you might be interested in the SPL Object Storage class.
根据您的需要,您可能对 SPL 对象存储类感兴趣。
http://php.net/manual/en/class.splobjectstorage.php
http://php.net/manual/en/class.splobjectstorage.php
It lets you use objects as keys, has an interface to count, get the hash and other goodies.
它让你可以使用对象作为键,有一个接口来计数、获取哈希和其他好东西。
$s = new SplObjectStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o2->foo = 'bar';
$s[$o1] = 'baz';
$s[$o2] = 'bingo';
echo $s[$o1]; // 'baz'
echo $s[$o2]; // 'bingo'
回答by Eric Leschinski
Create a Java like HashMap in PHP with O(1) read complexity.
在 PHP 中创建一个类似于 HashMap 的 Java,读取复杂度为 O(1)。
Open a phpsh terminal:
打开一个 phpsh 终端:
php> $myhashmap = array();
php> $myhashmap['mykey1'] = 'myvalue1';
php> $myhashmap['mykey2'] = 'myvalue2';
php> echo $myhashmap['mykey2'];
myvalue2
The complexity of the $myhashmap['mykey2']
in this case appears to be constant time O(1), meaning that as the size of $myhasmap approaches infinity, the amount of time it takes to retrieve a value given a key stays the same.
$myhashmap['mykey2']
在这种情况下的复杂性似乎是常数时间 O(1),这意味着随着 $myhasmap 的大小接近无穷大,检索给定键值所需的时间量保持不变。
Evidence the php array read is constant time:
php数组读取的证据是恒定时间:
Run this through the PHP interpreter:
通过 PHP 解释器运行:
php> for($x = 0; $x < 1000000000; $x++){
... $myhashmap[$x] = $x . " derp";
... }
The loop adds 1 billion key/values, it takes about 2 minutes to add them all to the hashmap which may exhaust your memory.
该循环添加了 10 亿个键/值,将它们全部添加到哈希图中大约需要 2 分钟,这可能会耗尽您的内存。
Then see how long it takes to do a lookup:
然后看看做一次查找需要多长时间:
php> system('date +%N');echo " " . $myhashmap[10333] . " ";system('date +%N');
786946389 10333 derp 789008364
So how fast is the PHP array map lookup?
那么 PHP 数组映射查找的速度有多快呢?
The 10333
is the key we looked up. 1 million nanoseconds == 1 millisecond. The amount of time it takes to get a value from a key is 2.06 million nanoseconds or about 2 milliseconds. About the same amount of time if the array were empty. This looks like constant time to me.
这10333
是我们查找的关键。100 万纳秒 == 1 毫秒。从键中获取值所需的时间为 206 万纳秒或大约 2 毫秒。如果数组为空,时间大约相同。这对我来说似乎是恒定的时间。
回答by klausinho
$fruits = array (
"fruits" => array("a" => "Orange", "b" => "Banana", "c" => "Apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
echo $fruits["fruits"]["b"]
outputs 'Banana'
输出'香蕉'
回答by Gert Jan Schoneveld
HashMap that also works with keys other than strings and integers with O(1) read complexity (depending on quality of your own hash-function).
HashMap 也适用于字符串和整数以外的键,读取复杂度为 O(1)(取决于您自己的哈希函数的质量)。
You can make a simple hashMap yourself. What a hashMap does is storing items in a array using the hash as index/key. Hash-functions give collisions once in a while (not often, but they may do), so you have to store multiple items for an entry in the hashMap. That simple is a hashMap:
您可以自己制作一个简单的 hashMap。hashMap 所做的是使用散列作为索引/键将项目存储在数组中。散列函数偶尔会产生冲突(不经常,但它们可能会发生),因此您必须在 hashMap 中为一个条目存储多个项目。一个简单的 hashMap:
class IEqualityComparer {
public function equals($x, $y) {
throw new Exception("Not implemented!");
}
public function getHashCode($obj) {
throw new Exception("Not implemented!");
}
}
class HashMap {
private $map = array();
private $comparer;
public function __construct(IEqualityComparer $keyComparer) {
$this->comparer = $keyComparer;
}
public function has($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $item) {
if ($this->comparer->equals($item['key'], $key)) {
return true;
}
}
return false;
}
public function get($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $item) {
if ($this->comparer->equals($item['key'], $key)) {
return $item['value'];
}
}
return false;
}
public function del($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $index => $item) {
if ($this->comparer->equals($item['key'], $key)) {
unset($this->map[$hash][$index]);
if (count($this->map[$hash]) == 0)
unset($this->map[$hash]);
return true;
}
}
return false;
}
public function put($key, $value) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
$this->map[$hash] = array();
}
$newItem = array('key' => $key, 'value' => $value);
foreach ($this->map[$hash] as $index => $item) {
if ($this->comparer->equals($item['key'], $key)) {
$this->map[$hash][$index] = $newItem;
return;
}
}
$this->map[$hash][] = $newItem;
}
}
For it to function you also need a hash-function for your key and a comparer for equality (if you only have a few items or for another reason don't need speed you can let the hash-function return 0; all items will be put in same bucket and you will get O(N) complexity)
为了让它发挥作用,您还需要一个用于键的散列函数和一个用于相等的比较器(如果您只有几个项目或出于其他原因不需要速度,您可以让散列函数返回 0;所有项目都将是放入同一个桶中,您将获得 O(N) 复杂度)
Here is an example:
下面是一个例子:
class IntArrayComparer extends IEqualityComparer {
public function equals($x, $y) {
if (count($x) !== count($y))
return false;
foreach ($x as $key => $value) {
if (!isset($y[$key]) || $y[$key] !== $value)
return false;
}
return true;
}
public function getHashCode($obj) {
$hash = 0;
foreach ($obj as $key => $value)
$hash ^= $key ^ $value;
return $hash;
}
}
$hashmap = new HashMap(new IntArrayComparer());
for ($i = 0; $i < 10; $i++) {
for ($j = 0; $j < 10; $j++) {
$hashmap->put(array($i, $j), $i * 10 + $j);
}
}
echo $hashmap->get(array(3, 7)) . "<br/>";
echo $hashmap->get(array(5, 1)) . "<br/>";
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(-1, 9))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(6))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(1, 2, 3))? 'true': 'false') . "<br/>";
$hashmap->del(array(8, 4));
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
Which gives as output:
作为输出给出:
37
51
true
false
false
false
false