试图获取非对象codeigniter视图的属性

时间:2018-01-19 03:27:56

标签: php codeigniter

我尝试将控制器中的foreach数据添加到我的视图中,但我在trying to get property of non-object

中收到错误foreach($menu_down as $menu_downs)

控制器

public function index() {
    $data['menu'] = $this->M_home->tampil_menu_utama();
    $data2 = array(); //initialize your variable with array; 

    foreach ($data['menu'] as $menus) {
        $idmenu = $menus->menuid;
        // echo $idmenu."<br>";
        // print_r($data['menu_down']); 
        $data2['menu_down'][] = $this->M_home->tampil_menu_down($idmenu);
        // print_r($data);
    }
    // print_r($data['menu_down']);
    $this->load->view('head', array_merge($data, $data2));
    $this->load->view('home');
    $this->load->view('foot');
}

模型

function tampil_menu_down($idmenu){        
    $query = $this->db->query("SELECT menuname FROM `menu_master` WHERE root='".$idmenu."'");        
    return $query->result();
}

查看

<?php foreach($menu as $menus){ ?>

    <li class="treeview">
      <a href="#"><i class="fa fa-link"></i>
        <span><?php echo $menus->menuname ?></span>
        <span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span>
      </a>
      <ul class="treeview-menu">

        <?php foreach($menu_down as $menu_downs){ //error ?>

          <li><a href="#"><?php echo $menu_downs->menuname ?></a></li>

        <?php } ?>

      </ul>
    </li>

<?php } ?>

2 个答案:

答案 0 :(得分:0)

尝试在视图中打印 $ menus 并检查它是对象还是数组。如果是数组,则无法像 $ menus-&gt; menuname

那样访问它

如果可能,请在此处发布输出。

答案 1 :(得分:0)

你不应该以这种方式使用数组合并,因为它有意想不到的效果。

请改为:

public function index() {
    $menu = $this->M_home->tampil_menu_utama();
    $data = array();
    foreach ($menu as $menus) {
        $data[] = $this->M_home->tampil_menu_down($menus->menuid);
    }
    $this->load->view('head', array('menu' => $menu, 'menu_down' => $data));
    $this->load->view('home');
    $this->load->view('foot');
}

如果失败,请尝试:

    <?php foreach($menu_down as $k => $v){ //error ?>

      <li><a href="#"><?php echo $v->menuname ?></a></li>

    <?php } ?>