SPL提供了许多数据结构,如双向链表,堆栈,优先队列,对象存储,案例如下。
//1.SplDoublyLinkedList 双向链表
header('Content-type:text/html;charset=UTF-8');
$list = new SplDoublyLinkedList();
$list->push('one');
$list->push('two');//尾部插入
$list->push('three');
$list->unshift('zero');//头部插入
$list->add(2,'before_two');//根据索引插入
//echo '尾部删除'.$list->pop().'<br>';
//echo '首部删除'.$list->shift().'<br>';
$list->offsetSet(1,'one_replace');
echo $list->bottom().'----<br>';//第一个
echo $list->top().'-----<br>';//最后一个
//$list->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);逆序访问
$list->rewind();//重置当前指针指向头部
$s = $list->serialize();
//echo $s;//序列化
while($list->valid()){
echo $list->current().'<br>';//prev() 前一个
$list->next();
}
echo '====================<br>';
//2.SplStack类通过使用一个双向链表来提供栈的主要功能。
$q = new SplStack();
$q->push('one');
$q->push('two');
$q->push('three');
while(!$q->isEmpty()){
echo $q->pop().'<br>';
}
echo '====================<br>';
//3.SplQueue 类通过使用一个双向链表来提供队列的主要功能。
$q = new SplQueue();
$q->enqueue('one');
$q->enqueue('two');
$q->enqueue('three');
while($q->isEmpty()==false){
echo $q->dequeue().'<br>';
}
echo '====================<br>';
//4.堆 The SplHeap class provides the main functionalities of a Heap.
//通过最小堆构建一个树
/*
* 1
|
+-----+--+--+-----+
| | | |
2 3 4 5
| | |
+ +-+-+ +
| | | |
7 6 8 9
|
+-+-+
| |
10 11
*/
$h = new SplMinHeap();
// [parent, child]
$h->insert([9, 11]);
$h->insert([0, 1]);
$h->insert([1, 2]);
$h->insert([1, 3]);
$h->insert([1, 4]);
$h->insert([1, 5]);
$h->insert([3, 6]);
$h->insert([2, 7]);
$h->insert([3, 8]);
$h->insert([5, 9]);
$h->insert([9, 10]);
for ($h->top(); $h->valid(); $h->next()) {
list($parentId, $myId) = $h->current();
echo "$myId ($parentId)<br>";
}
echo '====================<br>';
//堆排序
$heap = new SplMaxHeap();
$heap->insert(1);
$heap->insert(4);
$heap->insert(3);
$heap->insert(2);
while($heap->valid()){
//echo $heap->current().'<br>';//获取
//$heap->next();
echo $heap->extract().'<br>';
}
//4 3 2 1
echo '====================<br>';
// 5.优先队列
$pq = new SplPriorityQueue();
$pq->insert(1,5);
$pq->insert(3,4);
$pq->insert(2,6);
while($pq->valid()){
echo $pq->current().'<br>';
$pq->next();
}
// 6.定长数组,更快
$fa = new SplFixedArray(3);//
$fa[2] = 'three';
$fa[1] = 'two';
$fa[0] = 'one';
while($fa->valid()){ //
echo $fa->current();
$fa->next();
}
echo '====================<br>';
//7. SplObjectStorage 对象存储
$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));
//--对象当做索引
echo '====================<br>';
$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]);
}
image.png
image.png
image.png
image.png
image.png