-
Notifications
You must be signed in to change notification settings - Fork 0
/
arrayIterator.php
71 lines (64 loc) · 1.36 KB
/
arrayIterator.php
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
/**
* Created by PhpStorm.
* User: M2ez
* Date: 2016/3/31
* Time: 11:19
* E-mail:[email protected]
* webSite: http://www.m2ez.com
*/
$fruits = array(
'apples'=>'apple value',
'orange'=>'orange value',
'grape'=>'grape value',
'plum'=>'plum value'
);
print_r($fruits);
// 直接遍历
echo "*****use fruits directly\n\r";
foreach ($fruits as $key=>$val)
{
echo $key . ':' . $val . "\n\r";
}
// 使用ArrayIterator遍历数组
echo "*****use fruits ArrayIterator in for\n\r";
$obj = new ArrayObject($fruits);
$it = $obj->getIterator();
foreach ($it as $key=>$val)
{
echo $key . ':' . $val . "\n\r";
}
// 使用while对数组进行遍历
echo "*****use fruits ArrayIterator in while\n\r";
$it->rewind();
while ($it->valid())
{
echo $it->key() . ':' . $it->current() . "\n\r";
$it->next();
}
// 跳过某些元素进行打印
echo "*****use seek before while\n\r";
$it->rewind();
if($it->valid())
{
$it->seek(1);
while($it->valid())
{
echo $it->key() . ':' . $it->current() . "\n\r";
$it->next();
}
}
// key排序
echo "*****use ksort\n\r";
$it->ksort();// 对key进行字典序排序
foreach ($it as $key=>$val)
{
echo $key . ':' . $val . "\n\r";
}
// value排序
echo "*****use asort\n\r";
$it->asort();// 对value进行字典序排序
foreach ($it as $key=>$val)
{
echo $key . ':' . $val . "\n\r";
}