2013-04-11 108 views
0

我在php中創建了一個函數,我用這個函數的目標是在HTML選擇標記中打印以下行。在HTML選擇標記中使用php函數

<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 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> 

有人能指出我出錯的地方,我弄不明白。

+0

不要忘了逃跑$鍵和$值,你輸出他們使用'ヶ輛()'! – 2013-04-11 11:24:09

回答

0

我想你可以試試下面一行:

$str = ""; 
foreach($names as $key => $value){ 
    $str .= '<option value="' . $key . '" ' . (($product[$name . '_id'] == $key) ?  'selected' : '') . '>' . $value . '</option>'; 
} 
return $str; 

1)使用空字符串,而不是空。 2)空間$鍵後,在價值

希望這有助於

0

你的問題是你試圖單獨返回每一行。 但您的功能在第一次返回後將不會繼續。 這應該工作:

$str = ''; 
foreach($names as $key => $value){ 
    $str = $str.'<option value="' . $key . '"' . $product[$name . '_id'] == $key ? 'selected' : null . '>' . $value . '</option>'; 
} 
return str; 
0
$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 ; ?>