很抱歉,如果这太明显但我正在学习如何处理数组而且我完全陷入困境,不能继续:(
拥有以下数组:
$myarray: array =
0:array=
0:string=-
1:string=-
1:array=
0:string=AA1
1:string=Book title 1
2:string=Author 1
2:array=
0:string=AA2
1:string=Book title 2
2:string=Author2
.
.
我需要在html表单中构建一个select,以这种方式填充它:
<select id="bookTitles">
<option value="-" selected="selected">Select..</option>
<option value="AA1"> Book title 1</option>
<option value="AA2"> Book title 2</option>
.
.
</select>
如何循环$myarray
来执行此操作?
非常感谢!
答案 0 :(得分:1)
试试这个:
<select name = "theSelect">
<option value = "-" selected = "selected">Select...</option>
<?php
array_shift($myarray); // take off the first element that is empty
foreach( $myarray as $k => $v) {
echo('<option value = "' . $v[0] . '">' . $v[1] . '</option>');
}
?>
</select>
答案 1 :(得分:0)
<select id="bookTitles">
<option value="-" selected="selected">Select..</option>
<?php foreach ($myarray as $value) : ?>
<option value="<?php echo $value[0]; ?>"> <?php echo $value[1]; ?></option>
<?php endforeach; ?>
</select>
一些注意事项:
:
和endforeach;
代替{
和}
,因为它在输出HTML时通常看起来更干净<?=$value[0]?>
(read more on this here)