dongposhi8677 2015-11-15 18:26

# 循环遍历PHP多维数组

Im trying to create a 2D array with a specific number of rows and cols which I have stored as the variable \$n ; so if \$n was 5, I would have 5 rows and 5 cols, all with random numbers. I have created a for loop (as shown below) that generates the correct amount of rows but I cannot figure out how to do the same with the columns at the same time. The code I have at the moment is shown below.

``````<?php

\$n = 3;

for(\$i=0; \$i<=\$n; \$i++) {
\$value[\$i][0] = rand(1,20);
\$value[\$i][1] = rand(1,20);
\$value[\$i][2] = rand(1,20);
\$value[\$i][3] = rand(1,20);
}

print "<table>";
for(\$j=0; \$j<\$n; \$j++)  { // Runs the loop times \$n
print "<tr>";
for(\$k=0; \$k<\$n; \$k++)  { // Runs the loop times \$n
print "<td>" . \$value[\$j][\$k] . "</td>";
}
print   "</tr>";
}
print   "</table>";

?>
``````

Any help would be appreciated in learning to create this loop of the array. Thanks in advance.

• 写回答

#### 2条回答默认 最新

• 普通网友 2015-11-15 18:30
关注

You need a second loop inside the first loop:

``````for(\$i=0; \$i<=\$n; \$i++) { // rows
for(\$j=0; \$j<=\$n; \$j++) { // columns
\$value[\$i][\$j] = rand(1,20);
}
}
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 如何卸载arcgis 10.1 data reviewer for desktop
• ¥15 共享文件夹会话中为什么会有WORKGROUP
• ¥15 关于#python#的问题：使用ATL02数据解算光子脚点的坐标(操作系统-windows)
• ¥115 关于#python#的问题：未加密前两个软件都可以打开，加密后只有A软件可打开，B软件可以打开但读取不了数据
• ¥15 在matlab中Application Compiler后的软件无法打开
• ¥15 想问一下STM32创建工程模板时遇到得问题
• ¥15 Fiddler抓包443
• ¥20 Qt Quick Android 项目报错及显示问题
• ¥15 而且都没有 OpenCVConfig.cmake文件我是不是需要安装opencv，如何解决？
• ¥15 oracleBIEE analytics