PHP 数组抽象的数据集合
本文最后更新于:2024年3月18日 凌晨
PHP 数组抽象的数据集合
几乎在每一个PHP程序中都要用到数组,除了用于存储集合的值以外,它们还被用于实现各种抽象的数据集合,在本节中,将介绍如何使用数组来实现集合(set)和堆栈(stack)
集合
数组允许你实现基本的集合操作:并集(union),交集(intersection)和差集(difference),每个集合都以数组表示,有很多各种各样的PHP函数可实现集合操作,集合中的值就是数组中的值,数组中的键不再被使用,但是通常可通过操作被保留。
两个集合的并集(union)是两个集合的所有元素,并删除重复的元素,array_merge()
和array_unique()
函数用于计算并集,下面得到两个数组的并集:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 function array_union ($a ,$b ) { $union = array_merge($a ,$b ); $union = array_unique($union ); return $union ; }$first = array (1 ,'two' ,3 );$second = array ('two' ,'three' ,'four' );$union = array_union($first ,$second ); print_r($union );Array ( [0 ] => 1 [1 ] => two [2 ] => 3 [3 ] => three [4 ] => four )
两个结合的交集(intersection)是它们公有元素的集合,PHP的内置函数array_intersection()
接收人一个数组作为参数,并且返回在每个数组中都存在的值的数组,如果有多个键有相同的值,保存值的第一个键。
另外一个在数组集合上常用的函数是得到差集(difference)的函数,即在一个数组中出现且不在另一个数组中出现的值,array_diff()
函数用于计算差集,返回一个数组,该数组中的值在第一个数组中出现而不在第二个数组中出现。
下面的代码是得到两个数组的差集:
1 2 3 4 5 6 7 8 9 10 $first = array (1 ,'two' ,3 );$second = array ('two' ,'three' ,'four' );$difference = array_diff($first ,$second ); print_r($difference );Array ( [0 ] => 1 [2 ] => 3 )
堆栈
后进后出(last-in first-out,LIFO)堆栈是一个常用的数据类型,虽然堆栈在PHP程序中不像其他程序中那样普遍,我们可以使用一对函数array_push()
和array_pop()
来创建堆栈,array_push()
函数和用$array[]赋值具有相同的作用,我们使用array_push()
是因为它强调一个事实,我们用堆栈工作,并且对应地使用array_pop()
让代码更加易于阅读,另外array_shift()
和array_unshift()
函数把数组作为队列(queue)对待。
堆栈在维持状态时很有用,下例提供一个简单的状态调试器,它允许你打印出一个到这点为止被调用的函数清单(即栈的跟踪,stack trace)
示例5-4 :状态调试器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 $call_trace = array ();function enter_function ($name ) { global $call_trace ; array_push($call_trace ,$name ); echo "Entering $name (stack is now" . join(' -> ' ,$call_trace ) . ')<br/>' ; }function exit_function ( ) { echo 'Exiting<br/>' ; global $call_trace ; array_pop($call_trace ); }function first ( ) { enter_function('first' ); exit_function(); }function second ( ) { enter_function('second' ); first(); exit_function();}function third ( ) { enter_function('third' ); second(); first(); exit_function(); } first(); third(); Entering first (stack is now: first) Exiting Entering third (stack is now: third) Entering second (stack is now: third -> second) Entering first (stack is now: third -> second -> first) Exiting Exiting Entering first (stack is now: third -> first) Exiting Exiting