php实现foreach遍历
使用 foreach 遍历数组
在 PHP 中,foreach 是遍历数组的常用方法,适用于索引数组和关联数组。
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
输出结果:
apple
banana
orange
遍历关联数组
对于关联数组,可以同时获取键和值:
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
输出结果:
name: John
age: 30
city: New York
遍历多维数组
对于多维数组,可以使用嵌套的 foreach 循环:
$users = [
["id" => 1, "name" => "Alice"],
["id" => 2, "name" => "Bob"],
["id" => 3, "name" => "Charlie"]
];
foreach ($users as $user) {
foreach ($user as $key => $value) {
echo "$key: $value ";
}
echo "\n";
}
输出结果:
id: 1 name: Alice
id: 2 name: Bob
id: 3 name: Charlie
引用方式遍历
如果需要修改原数组的值,可以使用引用方式:
$numbers = [1, 2, 3, 4];
foreach ($numbers as &$number) {
$number *= 2;
}
print_r($numbers);
输出结果:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
)
遍历对象
foreach 也可以遍历实现了 Iterator 接口的对象:
class MyIterator implements Iterator {
private $position = 0;
private $array = ['first', 'second', 'third'];
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->array[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->array[$this->position]);
}
}
$it = new MyIterator;
foreach($it as $key => $value) {
echo "$key: $value\n";
}
输出结果:
0: first
1: second
2: third






