数组内的 PHP 循环 [英] PHP Loop inside array
问题描述
如何在代码中的 array
中循环?
How can I loop inside an array
in my code?
这是我的脚本的静态版本:
This is the static version of my script:
$val=array(
array("value" => "Male","label" => "Male"),
array("value" => "Female","label" => "Femal"),
);
my_form("Gender","select","gender",$val,"",5);
然后,我需要从数据库中检索value
和label
.
Then, I need to retrieve the value
and label
from the database.
所以我将之前的代码自定义为:
So I customized my previous code to:
$div=array(
while($h = mysql_fetch_array($qwery)){
array("value" => "$h[id]","label" => "$h[div]"),
}
);
my_form("Division","select","id_div",$div,"",5);
当我运行它时,我得到这个错误信息
:
When I run it I get this Error message
:
解析错误:语法错误,意外的'while' (T_WHILE),期望')'
Parse error: syntax error, unexpected 'while' (T_WHILE), expecting ')'
有人可以帮我吗?
我想将连接数据从我的数据库循环到 :
I want to loop the join data from my database into :
输入类型="选择"
推荐答案
不能将循环直接用作数组中的值.相反,循环并为 while 循环的每次迭代添加每个数组.
You can't use a loop directly as a value in an array. Instead, loop over and add each array for each iteration of the while-loop.
使用 $div[] = "value"
,您可以将该值添加为该数组中的新元素.
Using $div[] = "value"
, you add that value as a new element in that array.
$div = array(); // Initialize the array
// Loop through results
while ($h = mysql_fetch_array($qwery)) {
// Add a new array for each iteration
$div[] = array("value" => $h['id'],
"label" => $h['div']);
}
这将创建一个二维数组,看起来(作为示例)像
This will create a two-dimensjonal array which would look (as an example) like
array(
array(
"value" => "Male",
"label" => "Male"
),
array(
"value" => "Female",
"label" => "Female"
)
);
...然后你可以用 foreach
来查看它来做你想做的事情.
...which you then can look through with a foreach
to do what you want with it.
如果您希望将其作为选择元素中的选项输出,您可以直接这样做
If you want this to be output as options in a select-element, you could just do that directly
<select name="sel">
<?php
while ($row = mysql_fetch_array($qwery)) {
echo '<option value="'.$row['id'].'">'.$row['div'].'</option>';
}
?>
</select>
这篇关于数组内的 PHP 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!