2013-08-01 54 views
2

我設置了codeignitor窗體的關聯數組,並且遇到了有關數據的foreach循環的問題。Codeignitor assosciative array - 在foreach循環中更改數組名稱

我有這樣的代碼 - 而現在我剛剛意識到我再次聲明變量名$ ARRAY_NAME作爲數組,而不是一個字符串,這就是爲什麼這一次不工作:

foreach ($search as $search_term){ 
$count++; 
$array_name = '$search'.$count; 

$array_name = array(
     'name' => 'search'.$count, 
     'id' => 'search'.$count, 
     'value' => set_value('search'.$count, $search_term), 
     'maxlength' => 80, 
     'size' => 30, 
     'class' => 'text-input', 
); 

}

但是,數組名稱被記錄爲$ array_name而不是$ search1,所以我顯然做錯了一些事情,我希望有人能指出我朝着正確的方向!

我也試過這樣:

foreach ($search as $search_term){ 
$count++; 
$array_name = '$search'.$count; 

'search'.$count = array(
     'name' => 'search'.$count, 
     'id' => 'search'.$count, 
     'value' => set_value('search'.$count, $search_term), 
     'maxlength' => 80, 
     'size' => 30, 
     'class' => 'text-input', 
); 

}

這就是我要尋找的最終結果,但將有6整體:

$search1 = array(
     'name' => 'search'.$count, 
     'id' => 'search'.$count, 
     'value' => set_value('search'.$count, $search_term), 
     'maxlength' => 80, 
     'size' => 30, 
     'class' => 'text-input', 
); 
$search2 = array(
     'name' => 'search2', 
     'id' => 'search2', 
     'value' => set_value('search2, $search_term), 
     'maxlength' => 80, 
     'size' => 30, 
     'class' => 'text-input', 
); 

任何幫助將不勝感激 - 我希望這只是我是一個白癡,錯過了明顯的東西!

編輯1:

對不起,我剛剛意識到我再次聲明變量名$ ARRAY_NAME作爲數組,而不是一個字符串,這就是爲什麼第一次不工作,但我仍然有點卡住如何做到這一點。所有的幫助仍然歡迎!

+0

你爲什麼不繼續創建一個陣列子陣像' $ searchs [0]'是你的第一個搜索數組,等等? –

回答

3

使用動態字符串中使用${'somestring'} =

foreach ($search as $search_term){ 
    $count++; 
    $array_name = '$search'.$count; 

    ${'search'.$count} = array(
     'name' => 'search'.$count, 
     'id' => 'search'.$count, 
     'value' => set_value('search'.$count, $search_term), 
     'maxlength' => 80, 
     'size' => 30, 
     'class' => 'text-input', 
    ); 
} 

雖然使用關聯數組會更好做一個變量

$searches = array(); 
foreach ($search as $search_term){ 
    $count++; 
    $array_name = '$search'.$count; 

    $searches['search'.$count] = array(
     'name' => 'search'.$count, 
     'id' => 'search'.$count, 
     'value' => set_value('search'.$count, $search_term), 
     'maxlength' => 80, 
     'size' => 30, 
     'class' => 'text-input', 
    ); 
} 

print_r($searches);