PHP中SPL提供的数据结构

Author Avatar
Mr-houzi 11月 21, 2017
  • 在其它设备中阅读本文章

整理一下PHP常用的四种数据结构

1.栈

代码:

1
2
3
4
5
6
7
$stack = new SplStack();
//入栈
$stack->push("data1\n");
$stack->push("data2\n");
//出栈
echo $stack->pop();
echo $stack->pop();

结果:

1
2
data2
data1

2.队列

代码:

1
2
3
4
5
6
7
8
//队列
$queue = new SplQueue();
//入队
$queue->enqueue("data1\n");
$queue->enqueue("data2\n");
//出队
echo $queue->dequeue();
echo $queue->dequeue();

结果:

1
2
data1
data2

3.堆(最小堆)

代码:

1
2
3
4
5
6
$heap = new SplMinHeap();
$heap->insert("data1\n");
$heap->insert("data2\n");
echo $heap->extract();
echo $heap->extract();

结果:

1
2
data1
data2

4.固定尺寸数组

代码:

1
2
3
4
5
6
$array = new SplFixedArray(10);
$array[0] = 'abc';
$array[5] = 'def';
$array[9] = 'g';
var_dump($array);

结果:

1
2
3
4
5
6
7
8
9
10
11
object(SplFixedArray)[4]
public 0 => string 'abc' (length=3)
public 1 => null
public 2 => null
public 3 => null
public 4 => null
public 5 => string 'def' (length=3)
public 6 => null
public 7 => null
public 8 => null
public 9 => string 'g' (length=1)

代码下载:http://cdn.mr-houzi.com/image/php-spl-dataStructure/PhpDataStructure.php