数组遍历 #
一、foreach遍历 #
1.1 基本语法 #
php
<?php
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
1.2 获取键名 #
php
<?php
$user = ['name' => 'John', 'age' => 25, 'city' => 'Beijing'];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}
1.3 修改元素 #
php
<?php
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as &$number) {
$number *= 2;
}
unset($number);
print_r($numbers);
1.4 遍历多维数组 #
php
<?php
$users = [
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Bob', 'age' => 35]
];
foreach ($users as $user) {
echo "{$user['name']} is {$user['age']} years old\n";
}
1.5 替代语法 #
php
<?php $items = ['apple', 'banana', 'cherry']; ?>
<ul>
<?php foreach ($items as $item): ?>
<li><?= htmlspecialchars($item) ?></li>
<?php endforeach; ?>
</ul>
二、for遍历 #
2.1 基本语法 #
php
<?php
$fruits = ['apple', 'banana', 'cherry'];
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "\n";
}
2.2 优化性能 #
php
<?php
$fruits = ['apple', 'banana', 'cherry'];
$count = count($fruits);
for ($i = 0; $i < $count; $i++) {
echo $fruits[$i] . "\n";
}
2.3 逆序遍历 #
php
<?php
$fruits = ['apple', 'banana', 'cherry'];
for ($i = count($fruits) - 1; $i >= 0; $i--) {
echo $fruits[$i] . "\n";
}
2.4 步长遍历 #
php
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for ($i = 0; $i < count($numbers); $i += 2) {
echo $numbers[$i] . "\n";
}
三、while遍历 #
3.1 配合each() #
php
<?php
$user = ['name' => 'John', 'age' => 25, 'city' => 'Beijing'];
reset($user);
while (list($key, $value) = each($user)) {
echo "$key: $value\n";
}
3.2 配合数组指针 #
php
<?php
$fruits = ['apple', 'banana', 'cherry'];
reset($fruits);
while ($fruit = current($fruits)) {
echo $fruit . "\n";
next($fruits);
}
四、数组指针函数 #
4.1 指针操作函数 #
| 函数 | 说明 |
|---|---|
| current() | 获取当前元素 |
| key() | 获取当前键名 |
| next() | 移动到下一个元素 |
| prev() | 移动到上一个元素 |
| end() | 移动到最后一个元素 |
| reset() | 移动到第一个元素 |
4.2 使用示例 #
php
<?php
$fruits = ['apple', 'banana', 'cherry', 'date'];
echo current($fruits);
echo key($fruits);
next($fruits);
echo current($fruits);
end($fruits);
echo current($fruits);
reset($fruits);
echo current($fruits);
4.3 遍历示例 #
php
<?php
$fruits = ['apple', 'banana', 'cherry'];
reset($fruits);
while (key($fruits) !== null) {
echo key($fruits) . ' => ' . current($fruits) . "\n";
next($fruits);
}
五、list()解构 #
5.1 基本用法 #
php
<?php
$user = ['John', 25, 'Beijing'];
list($name, $age, $city) = $user;
echo "$name, $age, $city";
[$name, $age, $city] = $user;
echo "$name, $age, $city";
5.2 跳过元素 #
php
<?php
$user = ['John', 25, 'Beijing'];
list($name, , $city) = $user;
echo "$name, $city";
5.3 嵌套解构 #
php
<?php
$data = [
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30]
];
foreach ($data as ['name' => $name, 'age' => $age]) {
echo "$name is $age years old\n";
}
5.4 在foreach中使用 #
php
<?php
$users = [
['John', 25],
['Jane', 30],
['Bob', 35]
];
foreach ($users as [$name, $age]) {
echo "$name is $age years old\n";
}
六、数组迭代器 #
6.1 ArrayIterator #
php
<?php
$fruits = ['apple', 'banana', 'cherry'];
$iterator = new ArrayIterator($fruits);
while ($iterator->valid()) {
echo $iterator->key() . ' => ' . $iterator->current() . "\n";
$iterator->next();
}
6.2 IteratorAggregate #
php
<?php
class Collection implements IteratorAggregate
{
private array $items = [];
public function add($item): void
{
$this->items[] = $item;
}
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->items);
}
}
$collection = new Collection();
$collection->add('apple');
$collection->add('banana');
foreach ($collection as $item) {
echo $item . "\n";
}
七、遍历技巧 #
7.1 同时遍历多个数组 #
php
<?php
$names = ['John', 'Jane', 'Bob'];
$ages = [25, 30, 35];
for ($i = 0; $i < count($names); $i++) {
echo "{$names[$i]} is {$ages[$i]} years old\n";
}
7.2 使用array_map #
php
<?php
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(fn($n) => $n ** 2, $numbers);
print_r($squared);
7.3 使用array_walk #
php
<?php
$user = ['name' => 'John', 'age' => 25, 'city' => 'Beijing'];
array_walk($user, function($value, $key) {
echo "$key: $value\n";
});
7.4 带索引的遍历 #
php
<?php
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $index => $fruit) {
echo ($index + 1) . ". $fruit\n";
}
八、实际应用 #
8.1 表格生成 #
php
<?php
$users = [
['name' => 'John', 'age' => 25, 'city' => 'Beijing'],
['name' => 'Jane', 'age' => 30, 'city' => 'Shanghai'],
['name' => 'Bob', 'age' => 35, 'city' => 'Guangzhou']
];
?>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?= htmlspecialchars($user['name']) ?></td>
<td><?= $user['age'] ?></td>
<td><?= htmlspecialchars($user['city']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
8.2 导航菜单 #
php
<?php
$menu = [
'home' => '首页',
'products' => '产品',
'about' => '关于我们',
'contact' => '联系我们'
];
?>
<nav>
<ul>
<?php foreach ($menu as $slug => $label): ?>
<li>
<a href="/<?= $slug ?>"><?= $label ?></a>
</li>
<?php endforeach; ?>
</ul>
</nav>
8.3 数据导出 #
php
<?php
function exportToCsv(array $data, string $filename): void
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$output = fopen('php://output', 'w');
if (!empty($data)) {
fputcsv($output, array_keys($data[0]));
foreach ($data as $row) {
fputcsv($output, $row);
}
}
fclose($output);
}
九、性能优化 #
9.1 避免重复计算 #
php
<?php
$items = range(1, 10000);
for ($i = 0, $count = count($items); $i < $count; $i++) {
}
for ($i = 0; $i < count($items); $i++) {
}
9.2 使用foreach代替for #
php
<?php
$items = ['a', 'b', 'c'];
foreach ($items as $item) {
echo $item;
}
for ($i = 0; $i < count($items); $i++) {
echo $items[$i];
}
9.3 引用传递优化 #
php
<?php
$items = range(1, 10000);
foreach ($items as &$item) {
$item *= 2;
}
unset($item);
foreach ($items as $key => $item) {
$items[$key] *= 2;
}
十、总结 #
本章学习了:
- foreach遍历
- for遍历
- while遍历
- 数组指针函数
- list()解构
- 数组迭代器
- 遍历技巧
- 性能优化
下一章将学习数组函数。
最后更新:2026-03-26