将多维数组从控制器传递到Codeigniter

时间:2016-05-09 16:43:23

标签: arrays codeigniter multidimensional-array

我正在尝试创建一个可用于多种建筑类型的函数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是未达到预期结果的尝试。 echo的最后两个View给出了预期的结果,但我想使用通用变量来避免为每种建筑类型编写$hotel['title']$restaurant['title'] ....

2 个答案:

答案 0 :(得分: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
    }

}

答案 1 :(得分:0)

我不知道我是否理解你,但我知道你有一个阵列 像

$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>";
    }
}