2010-01-24 42 views
0

那麼,我不斷改進我的表格生成類,並堅持返回country_data數組中的所有國家元素。只有前兩個元素顯示在下拉選項中。在課堂上的foreach:我不能返回arr中的所有元素

這裏是下拉類:

 
//drop down form class 
class DropDown 
{ 
    function __construct ($form, $field_label, $field_name, $field_desc, $dropdown_data, $locale){ 
    $this->form = $form; 
    $this->field_label = $field_label; 
    $this->field_name = $field_name; 
    $this->field_desc = $field_desc; 
    $this->dropdown_data = $dropdown_data; 
    $this->locale = $locale; 
    } 

    function getNotRequiredData(){ 
    global $notReqArry; 
    return $notReqArry[$this->locale]; 
    } 

    function getValue(){ 
    return $_POST[$this->field_name]; 
    } 

    function option(){ 
    foreach ($this->dropdown_data as $key=>$value){ 
     return $options = sprintf('%s',$key,$value); 
    }; 
    } 
    function dropdown(){ 
    return $select_start = "field_name\">$this->field_desc".$this->option().""; 
    } 

    function getLabel(){ 
    $non_req = $this->getNotRequiredData(); 
    $req = in_array($this->field_name, $non_req) ? '' : '*'; 
    return $this->field_label ? $req . $this->field_label : ''; 
    } 

    function __toString(){ 
    $id = $this->field_name; 
    $label = $this->getLabel(); 
    $field = $this->dropdown(); 
    return 'field_name.'">'.$label.''.$field.''; 
    } 
} 

我使用額外的選項額外功能:

 
function generateForm ($lang,$country_list){ 

    switch($lang) 
    { 
    case 'en-US': 
     //create EN web form 
     echo $countryField = new DropDown ($form, 'Country', 'form_country', '--Select Country--', $country_list, 'en-US'); 
    break; 
    case 'fr-FR': 
     //create FR web form 
    break; 
    case 'de-DE': 
     //create DE web form 
    break; 
    case 'ja-JP': 
     //create JA web form 
    break; 
    default: 
     //create default web form 
     print('foooo'); 
    }; 
} 

我呼籲generateForm樂趣在頁面的底部。

 
$lang='en-US'; 
echo generateForm ($lang,$country_list); 

在前面的問題,一位專家提到的foreach不反對的$鍵和$價值,但我不明白,我需要更多的邏輯就在這裏。是的,我真的是PHP新手,對AS有很短的經驗。我需要幫助。

謝謝。

+3

隨便講話中的「ele」和「arr」等縮略語使得理解你在說什麼變得更加痛苦。打出額外的'唉'真的很難嗎? – 2010-01-25 00:00:15

+0

對不起,我修正了這個問題。 ;-) – chris 2010-01-25 01:12:38

+1

確保您接受正確的答案! = D – 2010-01-25 02:56:23

回答

3

您的選項函數試圖遍歷所有可用的選項,但始終只返回第一個選項。改爲:

function options(){ 
    $options = ''; 
    foreach ($this->dropdown_data as $key=>$value){ 
    $options .= sprintf('<option value="%s">%s</option>',$key,$value); 
    }; 
    return $options; 
} 
+0

非常感謝Cryo,它解決了上述問題。 ;-) – chris 2010-01-25 01:14:07

+0

很高興聽到它的克里斯。如果你可以點擊我答案旁邊的複選框來標記它是正確的,它會讓其他人知道你的問題得到了答案(並給我一點代表獎金)。 – nortron 2010-01-27 08:45:39

2

根據你的代碼,你的下拉列表中有兩個元素,你應該只有一個元素,這是一個驚喜。因爲你的功能

function options(){ 
foreach ($this->dropdown_data as $key=>$value){ 
    return $options = sprintf('%s',$key,$value); 
}; } 

只返回它從數組中獲得的第一個選項,然後退出循環。將所有物品收集在一起,並返回一堆,或者在某個外部循環內調用選項提取器,它將起作用。