[英]Using php function within HTML select tag
我在php中創建了一個函數,此函數的目標是在HTML select標記中打印以下行。
<option value="<?php echo $key . $product[$name . '_id'] == $key ? 'selected' : null ?>"><?php echo $value ?></option>
這是我想出的:
function Select($name){
$ids = array();
$values = array();
$query1 = $sql->query("SELECT * FROM '$name'");
while($fetch = $query1->fetch_assoc()){
array_push($ids, $fetch[$name . '_id']);
array_push($values, $fetch[$name]);
}
$names = array_combine($ids, $values);
foreach($names as $key => $value){
return '<option value="' . $key . '"' . $product[$name . '_id'] == $key ? 'selected' : null . '>' . $value . '</option>';
}
}
這似乎不起作用,但是當我直接將其放在HTML select標記中時,它確實起作用。 看起來像這樣:
<select name="type" class="chozen" id="type">
<?php
$brand_ids = array();
$brand_values = array();
$query1 = $sql->query("SELECT * FROM brands");
while($brand = $query1->fetch_assoc()){
array_push($brand_ids, $brand['brand_id']);
array_push($brand_values, $brand['brand']);
}
$brands = array_combine($brand_ids, $brand_values);
foreach($brands as $key => $value){
?>
<option value="<?php echo $key ?>"<?php echo $product['brand_id'] == $key ? 'selected' : null ?>><?php echo $value; ?></option>
<?php
}
?>
</select>
有人可以指出我出了問題的地方,我無法弄清楚。
您的問題是您試圖分別返回每一行。 但是您的函數在第一次返回后將不會繼續。 這應該工作:
$str = '';
foreach($names as $key => $value){
$str = $str.'<option value="' . $key . '"' . $product[$name . '_id'] == $key ? 'selected' : null . '>' . $value . '</option>';
}
return str;
$brands = array() ;
$query1 = $sql->query("SELECT * FROM brands");
while($brand = $query1->fetch_assoc()){
$brands[$brand['brand_id']] = $brand ; //Just use brand_id as keys in the array
}
if (!empty($brands)): ?>
<select name="type" class="chozen" id="type">
<?php foreach($brands as $id => $brand): ?>
<option value="<?php echo $brand['brand'] ; ?>"<?php echo ($brand['brand_id'] == $id ? 'selected' : ""); ?> ><?php echo $brand['brand'] ; ?></option>
<?php endforeach ; ?>
</select>
<?php else : ?>
<div>No brands to display!</div>
<?php endif ; ?>
我認為您可以嘗試以下代碼:
$str = "";
foreach($names as $key => $value){
$str .= '<option value="' . $key . '" ' . (($product[$name . '_id'] == $key) ? 'selected' : '') . '>' . $value . '</option>';
}
return $str;
1)使用空字符串而不是null。 2)$ key值后的空格
希望對你有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.