我有一个从用户表单创建的多维数组。我想在foreach循环中从循环中的某个键开始迭代数组。由于某些原因,我下面的代码不工作。
$i = 3;
foreach ($data as $val) {
echo $val[$i] . " : " . $val['value'] . "<br />";
$i++;
}
输出:Array (
[0] => Array ( [name] => name [value] => name )
[1] => Array ( [name] => code [value] => code )
[2] => Array ( [name] => description [value] => description )
[3] => Array ( [name] => unit-1 [value] => uni 1 )
[4] => Array ( [name] => unit-1-section-1 [value] => unit 1 sect 1 )
[5] => Array ( [name] => unit-2 [value] => unit 2 )
[6] => Array ( [name] => unit-2-section-1 [value] => unit 2 section 2 )
)
如您所见,我想从$data
数组中的第3个键开始。
只需使用常规的for
循环并开始3
键(我猜这就是你所说的"第三键",尽管它实际上是第四个):
for ($i = 3; $i < count($data); $i++) {
echo $data[$i]['name'] . " : " . $data[$i]['value'] . "<br />";
}
如果你想从$data中每个数组的第三个键开始:
foreach ($data as $val) {
$count = count($val);
for($i = 2; $i < $count; $i++)
echo $val[$i]['name'] . " : " . $val[$i]['value'] . "<br />";
}
}