php实现遍历
遍历数组
使用foreach循环可以方便地遍历数组中的每个元素。对于索引数组和关联数组都适用。
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
对于需要同时获取键和值的关联数组:

$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
遍历对象
实现Iterator接口可以让对象可被遍历。需要实现5个方法:current(), key(), next(), rewind(), valid()。
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";
}
使用数组函数遍历
array_walk()函数可以对数组每个元素应用用户自定义函数。

$numbers = [1, 2, 3, 4, 5];
array_walk($numbers, function($value, $key) {
echo "Key: $key, Value: $value\n";
});
array_map()将回调函数作用到给定数组的每个元素上。
$squared = array_map(function($n) {
return $n * $n;
}, $numbers);
print_r($squared);
递归遍历多维数组
对于多维数组,可以使用递归方式遍历。
function traverseArray($array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
traverseArray($value);
} else {
echo "$key => $value\n";
}
}
}
$multiDim = [
"fruit" => ["apple", "banana"],
"numbers" => [1, 2, 3]
];
traverseArray($multiDim);






