Codeigniter:在视图中解析数组数据

时间:2016-07-15 19:21:43

标签: php arrays codeigniter

我正在尝试获取帖子数据并将其过去以使用此类控制器进行查看

 $data['data']=$this->home->fetch_all_posts($this->news);
 $this->load->view('home',$data);

在我的视图中,当我执行print_r($ data)时,这就是我得到的

Array
(


    [0] => Array
        (
            [post] => stdClass Object
                (
                    [id] => 65
                    [date] => 2016-07-08
                    [title] =>  title of the news 
                    [content] => content of the news 
                    [type] => news
                )

            [attachments] => stdClass Object
                (
                    [id] => 2
                    [attachment_id] => 65
                    [type] => news
                    [path] => C:/wamp/www/school/ci/images/Jellyfish22.jpg
                )

        )

)

现在,当我试图预测这个并打印它不起作用时,请问我怎样才能打印这些值

3 个答案:

答案 0 :(得分:0)

CodeIginiter会将$data的值转换为自己的变量。因此$data['foobar']在视图中变为$foobar。您对$data['data']的使用可能会令人困惑和模糊,我建议您使用更具体的名称。

答案 1 :(得分:0)

试试这个

 if (!empty($data)) {
   foreach ($data as $row) 
   {  
     $row['post']->id;
     $row['post']->title;
     $row['attachments']->id;
     $row['attachments']->attachment_id;
   }
 }

答案 2 :(得分:0)

这应该是你所需要的......

$array = array(
  array('post'=> array(
           'id' => 65, 
           'date' => '2016-07-08',
           'title' => 'title of the news',
           'content' => 'content',
           'type' => 'news'
           ), 
        'attachments' => array(
           'id'=>2,
           'attachment_id' => 65, 
           'type'=> 'new', 
           'path' =>'C:/wamp'
         ))
  );

foreach ($array as $key => $value) {
  print_r($value['post']['id']); 
}