SPL是Standard PHP Library(PHP标准库)的缩写。
根据官方定义,它是"a collection of interfaces and classes that are meant to solve standard problems"。但是,目前在使用中,SPL更多地被看作是一种使object(物体)模仿array(数组)行为的interfaces和classes。
这几天学习SPL,这是我写的一点小笔记,望日后再次使用时能够想起点滴,SPL核心便是Iterator,熟练使用Iterator可以让我们更加方便的去操作数据.
ArrayIterator迭代器示例
1 <?php 2 $fruits = array 3 ( 4 "apple" => 'apple value', 5 "orange" => 'orange value', 6 "grape" => "grape value", 7 "plum" => "plum value" 8 ); 9 print_r($fruits); 10 echo "**** use fruits directly\n"; 11 foreach ($fruits as $key => $value) 12 { 13 echo $key . ":" . $value . "\n"; 14 } 15 //使用ArrayIterator遍历数组 16 $obj = new ArrayObject($fruits); 17 $it = $obj->getIterator(); 18 19 echo "***** use ArrayIterator in for\n"; 20 foreach ($it as $key => $value) 21 { 22 echo $key . ":" . $value . "\n"; 23 } 24 25 echo "***** use ArrayIterator in while\n"; 26 $it->rewind();//调用current之前要用rewind 27 while ($it->valid()) 28 { 29 echo $it->key() . ":" . $it->current()."\n"; 30 $it->next(); 31 } 32 //跳过某些元素进行打印 33 echo "***** use seek before while\n"; 34 $it->rewind(); 35 if ($it->valid()) 36 { 37 $it->seek(1); 38 while($it->valid()) 39 { 40 echo $it->key() . ":" . $it->current()."\n"; 41 $it->next(); 42 } 43 } 44 45 echo "***** use ksort\n"; 46 $it->ksort(); 47 foreach ($it as $key => $value) 48 { 49 echo $key . ":" . $value . "\n"; 50 } 51 52 echo "***** use asort\n"; 53 $it->asort(); 54 foreach ($it as $key => $value) 55 { 56 echo $key . ":" . $value . "\n"; 57 }