2016-11-11 146 views
0

如何在代码中循环使用array阵列内的PHP循环

这是我的脚本的静态版本:

$val=array(
array("value" => "Male","label" => "Male"), 
array("value" => "Female","label" => "Femal"), 
); 

my_form("Gender","select","gender",$val,"",5); 

然后,我需要从数据库中检索的valuelabel

所以我定制了自己以前的代码:

$div=array(
while($h = mysql_fetch_array($qwery)){ 
array("value" => "$h[id]","label" => "$h[div]"),  
} 
); 

my_form("Division","select","id_div",$div,"",5); 

当我运行它,我得到这个Error message

Parse error: syntax error, unexpected 'while' (T_WHILE), expecting ')'

谁能帮助我?

我想环路从我的数据库连接数据为:

input type="Select"

+0

你不能在数组中循环 – Blinkydamo

+1

为什么这个标签为'java'? –

回答

1

不能直接使用循环作为数组中的值。相反,循环并为while循环的每次迭代添加每个数组。使用$div[] = "value",您将该值作为该数组中的新元素添加。

$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']); 
} 

这将创建一个像

array(
    array(
     "value" => "Male", 
     "label" => "Male" 
    ), 
    array(
     "value" => "Female", 
     "label" => "Female" 
    ) 
); 

两dimensjonal阵列,它看起来(作为一个例子)...然后您可以通过看一个foreach做你想要做什么用。


如果你想这是作为输出的选择元素的选项,你可以只是做直接

<select name="sel"> 
    <?php 
    while ($row = mysql_fetch_array($qwery)) { 
     echo '<option value="'.$row['id'].'">'.$row['div'].'</option>'; 
    } 
    ?> 
</select> 
0

使用foreach可以帮助你。它给你更多的概述恕我直言。

$values = array(
    array("value" => "Male","label" => "Male"), 
    array("value" => "Female","label" => "Femal"), 
); 

<select name="Select"> 
<?php foreach ($val as $item): ?> 
    <option value="<?= $item['value']; ?>"><?= $item['label']; ?></option> 
<?php endforeach; ?> 
</select>