PHP多维数组 [英] PHP Multi dimentional array
本文介绍了PHP多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码。我不知道它为什么不起作用。
我试图用php for循环打印我的表格,但没有在网站上显示。
文档: foreach
This is my code. I don't know why it is not working. I was trying to print my table with php for loop, but nothing shows up on the website.Nothing
This is the two-dimentional array that I was trying to print out.
<!--Arrays of weapons-->
<?php
$weapons = array(
array("M4A1",1,78906,"TUCKER, LISBETH","SPC"),
array("M4A1",2,78915,"HATHAWAY, HANNAH","1LT"),
array("M4A1",3,78933,"HARRIS, LEE","SFC"),
array("M4A1",4,78934,"WELCH, BRAD","SSG"),
array("M9",1,1167552,"BLAND, MARGARET","CPT"),
array("M249",1,101032,"TYSON, MICHELLE","1SG"),
array("M249",2,101038,"MEDINA, TOBIAS","SPC"),
array("M240B",1,104104,"COSTA, JOSHUA","SSG"),
array("M2A1",1,1863848,"GARCIA, RIGOBERTO","SSG"),
array("MK-19",1,19369,"NEUPANE, KISHOR","SPC")
);
?>
This is the code that I was trying to use to print out.
<!--Create the Weapons List Table-->
<table border ="1">
<tr>
<th>Type</th>
<th>Buttstock #</th>
<th>Serial #</th>
<th>Name</th>
<th>Rank</th>
</tr>
<!--Put two-dimentinal arrays in the table-->
<?php foreach ($row = 0; $row < 10, $row++) {?>
<tr>
<?php for ($col = 0; $col < 5, $col++) {?>
<td><?php echo $weapons[$row][$col];?></td>
<?php }?>
</tr>
<?php }?>
</table>
解决方案
You have to use foreach
as foreach (array_expression as $value)
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
Like:
<?php
$weapons = array(
array("M4A1",1,78906,"TUCKER, LISBETH","SPC"),
array("M4A1",2,78915,"HATHAWAY, HANNAH","1LT"),
array("M4A1",3,78933,"HARRIS, LEE","SFC"),
array("M4A1",4,78934,"WELCH, BRAD","SSG"),
array("M9",1,1167552,"BLAND, MARGARET","CPT"),
array("M249",1,101032,"TYSON, MICHELLE","1SG"),
array("M249",2,101038,"MEDINA, TOBIAS","SPC"),
array("M240B",1,104104,"COSTA, JOSHUA","SSG"),
array("M2A1",1,1863848,"GARCIA, RIGOBERTO","SSG"),
array("MK-19",1,19369,"NEUPANE, KISHOR","SPC")
);
?>
<table border ="1">
<tr>
<th>Type</th>
<th>Buttstock #</th>
<th>Serial #</th>
<th>Name</th>
<th>Rank</th>
</tr>
<!--Put two-dimentinal arrays in the table-->
<?php foreach ($weapons as $weapon) {?>
<tr>
<?php foreach ( $weapon as $val ) {?>
<td><?php echo $val;?></td>
<?php }?>
</tr>
<?php }?>
</table>
This will result to:
Doc: foreach
这篇关于PHP多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文