📅  最后修改于: 2023-12-03 15:03:34.975000             🧑  作者: Mango
在 PHP 中使用 foreach 遍历二维数组时,若想获取当前行号,可以通过传递一个 $i
变量进行计数。
$array = array(
array("name" => "Tom", "age" => 18),
array("name" => "Jerry", "age" => 20),
array("name" => "Mickey", "age" => 15)
);
$i = 1;
foreach ($array as $value) {
// 获取当前行号
$i++;
echo "第 $i 行:" . $value["name"] . ",年龄:" . $value["age"] . "<br>";
}
$array = array(
array("name" => "Tom", "age" => 18),
array("name" => "Jerry", "age" => 20),
array("name" => "Mickey", "age" => 15)
);
$i = 0;
foreach ($array as $value) {
$i++;
echo "第 $i 行:" . $value["name"] . ",年龄:" . $value["age"] . "<br>";
}
输出结果如下:
第 1 行:Tom,年龄:18
第 2 行:Jerry,年龄:20
第 3 行:Mickey,年龄:15