[英]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.