2016-05-09 50 views
0

我試圖創建一個函數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'] ......每個建築類型。

+0

您已經顯示了與編程完全相同的結果。請解釋*您的*預期結果。你想達到什麼目的? – Sparky

回答

0

嘗試這樣的事情......

控制器:

public function index($data = NULL) { 
    $data['building_types']['hotel'] = $this->test('hotel'); 
    $data['building_types']['restaurant'] = $this->test('restaurant'); 

    $this->load->view('templates/default', $data); 
} 

查看:

foreach ($building_types as $building) { 

    foreach ($building as $value) { 
     echo $value; // whatever 
    } 

} 
0

我不`噸知道如果我理解你,但我明白,你有一個array like

$m_array = //come from model 
array(
    array(
      'title' => 'title', 
      '1'  => 'value1', 
      '2'  => 'value2', 
      '3'  => 'value3' 
    ), 
    array(
      'title' => 'title2', 
      '1'  => 'value1-2', 
      '2'  => 'value2-2', 
      '3'  => 'value3-2' 
    ), 
    array(
      'title' => 'title3', 
      '1'  => 'value1-3', 
      '2'  => 'value2-3', 
      '3'  => array('one' => 'v-one', 'two' => 'v-two') 
    ), 
    //etc 
    ); 

在您的視圖中

foreach($m_array as $item => $value){ 
    if(is_array($value)){ 
     foreach($value as $row => $value2){ 
      echo "<td>$item</td>"; 
      echo "<td>$row</td>"; 
      echo "<td>$value2</td>"; 
     } 
    } 
    else{ 
     echo "<td>$item</td>"; 
     echo "<td>$value</td>"; 
     echo "<td>-</td>"; 
    } 
} 
相關問題