// begin table centered with a border
print ('<table align = "center" border = 1>');
$index = 0; // initialize index
for ($i=0; $i <= $rows; $i++) {
print("<tr>"); // start row
for ($k=0; $k <= $columns; $k++) {
$index++; // increment the index value
// make sure we don’t exceed array bounds!
if ($index <= $num_items) {
tableContents( $images[$index],
$names[$index],
$item_num[$index],
$item_description[$index],
$item_price[$index],
$index);
}
else {
print("<td></td>"); // make blank cell
} // end if $index…
} // end inner for
print("</tr>"); // end row
} // end outer for…
print ("</table>"); // end table
我正在创建一个基本的 php 网页,将项目放在表中,但是我的 for 循环中出了点问题,我需要一点帮助。数组似乎不是从 0 开始的,我的 $index 变量应该从 0 开始然后递增,但它在开始时吐出了第 2 项。任何帮助将不胜感激!谢谢。
在选择元素之前,您必须$index++
,这就是为什么它从 1 开始。将其移到 if-else 语句结束后。
此外,根据下面的评论,请确保您的数组不会越界。也就是说,如果数组中有 n 个元素,则最后一个元素的索引为 n-1。所以,你可能想要$index < $num_items
,以及$k < $columns
和$i < $rows
。