我試圖創建一個函數test
將被用於多種建築類型,但我不能讓這些變量傳遞到視圖中。傳遞一個多維數組控制器與查看笨
控制器代碼:
public function index($data = NULL){
$data1 = $this->test('hotel');
$data2 = $this->test('restaurant');
$data = array_merge($data1,$data2);
$this->load->view('templates/default',$data);
}
public function test($building_type){
$data[$building_type]['title'] = 'this is a title for '.$building_type;
for ($i=1;$i<=3;$i++) {
$data[$building_type][$i] = $building_type.' button';
}
$data['building_type_array'] = ['hotel', 'restaurant'];
return $data;
}
查看代碼:
foreach ($building_type_array as $value) {
echo $value; // echoes 'hotel' and 'restaurant'
echo $value['title']; // throws 'Illegal string offset'
echo $value[3]; // echoes the 4th letter of 'hotEl' and 'resTaurant'
}
echo $building_type['title']; // Throws 'Undefined variable: building_type'
echo $hotel['title']; // echoes 'this is a title for hotel'
echo $hotel[3]; // echoes 'hotel button'
前四個echo
都試圖不給預期的結果。該View
的最後兩個echo
得到預期的結果,但我想用一個通用的變量,以避免編寫$hotel['title']
,$restaurant['title']
......每個建築類型。
您已經顯示了與編程完全相同的結果。請解釋*您的*預期結果。你想達到什麼目的? – Sparky