PHP 有内置的数据结构吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22401/
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
Does PHP have built-in data structures?
提问by Thomas Owens
I'm looking at the PHP Manual, and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in?
我正在查看PHP 手册,但没有看到有关大多数语言具有的数据结构的部分,例如列表和集合。我是瞎了眼还是 PHP 没有内置这样的东西?
采纳答案by Vincent
The only native data structure in PHP is array. Fortunately, arrays are quite flexible and can be used as hash tables as well.
PHP 中唯一的原生数据结构是数组。幸运的是,数组非常灵活,也可以用作哈希表。
However, there is SPL which is sort of a clone of C++ STL.
但是,SPL 是 C++ STL 的一种克隆。
回答by Frederik Krautwald
PHP offers data structures through the Standard PHP Library (SPL) basic extension, which is available and compiled by default in PHP 5.0.0.
PHP 通过标准 PHP 库 (SPL) 基本扩展提供数据结构,该扩展在 PHP 5.0.0 中默认可用并编译。
The data structures offered are available with PHP 5 >= 5.3.0, and includes:
提供的数据结构适用于 PHP 5 >= 5.3.0,包括:
Doubly Linked Lists
双向链表
A Doubly Linked List (DLL) is a list of nodes linked in both directions to each others. Iterator's operations, access to both ends, addition or removal of nodes have a cost of O(1) when the underlying structure is a DLL. It hence provides a decent implementation for stacks and queues.
双向链表 (DLL) 是双向链接的节点列表。当底层结构是 DLL 时,迭代器的操作、访问两端、添加或删除节点的成本为 O(1)。因此,它为堆栈和队列提供了一个不错的实现。
Heaps
堆
Heaps are tree-like structures that follow the heap-property: each node is greater than or equal to its children, when compared using the implemented compare method which is global to the heap.
堆是遵循堆属性的树状结构:当使用实现的对堆全局的比较方法进行比较时,每个节点都大于或等于其子节点。
Arrays
数组
Arrays are structures that store the data in a continuous way, accessible via indexes. Don't confuse them with PHP arrays: PHP arrays are in fact implemented as ordered hashtables.
数组是以连续方式存储数据的结构,可通过索引访问。不要将它们与 PHP 数组混淆:PHP 数组实际上是作为有序哈希表实现的。
Map
地图
A map is a datastructure holding key-value pairs. PHP arrays can be seen as maps from integers/strings to values. SPL provides a map from objects to data. This map can also be used as an object set.
映射是一种保存键值对的数据结构。PHP 数组可以看作是从整数/字符串到值的映射。SPL 提供了从对象到数据的映射。此地图也可用作对象集。
回答by Joseph Pecoraro
The associative array can be used for most basic data structures hashtable, queue, stack. But if you want something like a tree or heap I don't think they exist by default but I'm sure there are free libraries anywhere.
关联数组可用于大多数基本数据结构哈希表、队列、堆栈。但是如果你想要像树或堆这样的东西,我认为它们默认不存在,但我确信任何地方都有免费的库。
To have an array emulate a stack use array_push()to add and array_pop()to take off
让数组模拟堆栈用于array_push()添加和array_pop()起飞
To have an array emulate a queue use array_push()to enqueue and array_shift()to dequeue
让数组模拟队列用于array_push()入队和array_shift()出队
An associative array is a hash by default. In PHP they are allowed to have strings as indexes so this works as expected:
默认情况下,关联数组是散列。在 PHP 中,它们被允许将字符串作为索引,因此这可以按预期工作:
$array['key'] = 'value';
Finally, you can kind of emulate a binary tree with an array with the potential to have wasted space. Its useful if you know you're going to have a small tree. Using a linear array, you say for any index (i) you put its left child at index (2i+1) and right child at index (2i+2).
最后,您可以模拟带有可能浪费空间的数组的二叉树。如果你知道你将有一棵小树,它很有用。使用线性数组,您说对于任何索引 (i),您将其左子节点放在索引 (2i+1) 处,将右子节点放在索引 (2i+2) 处。
All of these methods are covered nicely in this articleon how to make JavaScript arrays emulate higher level data structures.
回答by RanjanaLK
Although this question is 8 years old I'm posting an answer because PHP 7 introduces an extension called dsproviding specialized data structures as an alternative to the array.
尽管这个问题已有 8 年历史,但我发布了一个答案,因为 PHP 7 引入了一个名为ds提供专用数据结构作为数组替代方案的扩展。
The ds,
的ds,
- uses the
Ds\namespace. - has 3 interfaces namely,
Collection,SequenceandHashable - has 8 classes namely,
Vector,Deque,Queue,PriorityQueue,Map,Set,Stack, andPair
- 使用
Ds\命名空间。 - 有 3 个接口,即
Collection,Sequence和Hashable - 有8类,即
Vector,Deque,Queue,PriorityQueue,Map,Set,Stack,和Pair
For more information checkout the Manualand also This blog posthas some awesome information including benchmarks.
回答by Konrad Rudolph
PHP has arrays which are actually associative arrays and can also be used as sets. Like many interpreted languages, PHP offers all this under one hood instead of providing different explicit data types.
PHP 的数组实际上是关联数组,也可以用作集合。像许多解释型语言一样,PHP 在一个引擎盖下提供所有这些,而不是提供不同的显式数据类型。
E.g.
例如
$lst = array(1, 2, 3);
$hsh = array(1 => "This", 2 => "is a", 3 => "test");
/Edit: Also, take a look in the manual.
/编辑:另外,看看手册。
回答by Corey
PHP's arraydoubles as both a list and a dictionary.
PHP 的数组兼作列表和字典。
$myArray = array("Apples", "Oranges", "Pears");
$myScalar = $myArray[0] // == "Apples"
Or to use it as an associative array:
或者将其用作关联数组:
$myArray = array("a"=>"Apples", "b"=>"Oranges", "c"=>"Pears");
$myScalar = $myArray["a"] // == "Apples"
回答by Markus
I think you might want to be a bit more specific, when you say data structures my mind goes in a few directions...
我想你可能想要更具体一点,当你说数据结构时,我的想法有几个方向......
Arrays - They are certainly well documented and available in. (http://us.php.net/manual/en/book.array.php)
数组 - 它们肯定有很好的文档记录并且可用。(http://us.php.net/manual/en/book.array.php)
SQL Data - Depends on the database you are using, but most are available. (http://us.php.net/manual/en/book.mysql.php)
SQL 数据 - 取决于您使用的数据库,但大多数都可用。( http://us.php.net/manual/en/book.mysql.php)
OOP - Depending on the version objects can be designed and implemented. (http://us.php.net/manual/en/language.oop.php) I had to search for OOP to find this on the php site.
OOP - 根据版本对象可以设计和实现。( http://us.php.net/manual/en/language.oop.php) 我不得不搜索 OOP 才能在 php 站点上找到它。
Hope that helps, sorry if it does not.
希望有帮助,如果没有,请见谅。
回答by mercutio
Of course PHP has data structures. The array in php is incredibly flexible. Some examples:
PHP当然有数据结构。php 中的数组非常灵活。一些例子:
$foo = array(
'bar' => array(1,'two',3),
'baz' => explode(" ", "Some nice words")
);
Then you have an absolute plethora of array functions available to map/filter/walk/etc the structures, or convert, flip, reverse, etc.
然后你有绝对过多的数组函数可用于映射/过滤/遍历/等结构,或转换、翻转、反转等。
回答by Abel Perez
You can always create your own if you don't feel PHP includes a specific type of data structure. For example, here is a simple Set data structure backed by an Array.
如果您不觉得 PHP 包含特定类型的数据结构,您可以随时创建自己的数据结构。例如,这是一个由 Array 支持的简单 Set 数据结构。
ArraySet: https://github.com/abelperez/collections/blob/master/ArraySet.php
ArraySet: https://github.com/abelperez/collections/blob/master/ArraySet.php
class ArraySet
{
/** Elements in this set */
private $elements;
/** the number of elements in this set */
private $size = 0;
/**
* Constructs this set.
*/
public function ArraySet() {
$this->elements = array();
}
/**
* Adds the specified element to this set if
* it is not already present.
*
* @param any $element
*
* @returns true if the specified element was
* added to this set.
*/
public function add($element) {
if (! in_array($element, $this->elements)) {
$this->elements[] = $element;
$this->size++;
return true;
}
return false;
}
/**
* Adds all of the elements in the specified
* collection to this set if they're not already present.
*
* @param array $collection
*
* @returns true if any of the elements in the
* specified collection where added to this set.
*/
public function addAll($collection) {
$changed = false;
foreach ($collection as $element) {
if ($this->add($element)) {
$changed = true;
}
}
return $changed;
}
/**
* Removes all the elements from this set.
*/
public function clear() {
$this->elements = array();
$this->size = 0;
}
/**
* Checks if this set contains the specified element.
*
* @param any $element
*
* @returns true if this set contains the specified
* element.
*/
public function contains($element) {
return in_array($element, $this->elements);
}
/**
* Checks if this set contains all the specified
* element.
*
* @param array $collection
*
* @returns true if this set contains all the specified
* element.
*/
public function containsAll($collection) {
foreach ($collection as $element) {
if (! in_array($element, $this->elements)) {
return false;
}
}
return true;
}
/**
* Checks if this set contains elements.
*
* @returns true if this set contains no elements.
*/
public function isEmpty() {
return count($this->elements) <= 0;
}
/**
* Get's an iterator over the elements in this set.
*
* @returns an iterator over the elements in this set.
*/
public function iterator() {
return new SimpleIterator($this->elements);
}
/**
* Removes the specified element from this set.
*
* @param any $element
*
* @returns true if the specified element is removed.
*/
public function remove($element) {
if (! in_array($element, $this->elements)) return false;
foreach ($this->elements as $k => $v) {
if ($element == $v) {
unset($this->elements[$k]);
$this->size--;
return true;
}
}
}
/**
* Removes all the specified elements from this set.
*
* @param array $collection
*
* @returns true if all the specified elemensts
* are removed from this set.
*/
public function removeAll($collection) {
$changed = false;
foreach ($collection as $element) {
if ($this->remove($element)) {
$changed = true;
}
}
return $changed;
}
/**
* Retains the elements in this set that are
* in the specified collection. If the specified
* collection is also a set, this method effectively
* modifies this set into the intersection of
* this set and the specified collection.
*
* @param array $collection
*
* @returns true if this set changed as a result
* of the specified collection.
*/
public function retainAll($collection) {
$changed = false;
foreach ($this->elements as $k => $v) {
if (! in_array($v, $collection)) {
unset($this->elements[$k]);
$this->size--;
$changed = true;
}
}
return $changed;
}
/**
* Returns the number of elements in this set.
*
* @returns the number of elements in this set.
*/
public function size() {
return $this->size;
}
/**
* Returns an array that contains all the
* elements in this set.
*
* @returns an array that contains all the
* elements in this set.
*/
public function toArray() {
$elements = $this->elements;
return $elements;
}
}
回答by Tajni
As for today (PHP 7.4), only native structure is an array. But from PHP7 extension DS appeared that includes new data structures and all of them are much faster than other implementations (including SPL recommended in accepted answer).
至于今天(PHP 7.4),只有原生结构是array. 但是从 PHP7 扩展 DS 出现,它包含新的数据结构,并且所有这些都比其他实现快得多(包括在接受的答案中推荐的 SPL)。
Interfaces: Collection, Hashable, Sequence
接口:Collection, Hashable,Sequence
Classes: Vector, Deque, Map, Pair, Set, Stack, Queue, PriorityQueue
类:Vector, Deque, Map, Pair, Set, Stack, Queue,PriorityQueue

