2015-02-06 44 views
0

首先原谅我,我是codeigniter框架的初学者。我想在视图中显示父数组的所有子内容。我假设我的数据检索部分已经完成,现在我需要知道如何使用foreach获取值。我用foreach,但我得到错误(非法字符串偏移量)。这是我得到我的页面的var_dump值。查看codeigniter中的数据

array(1) { 
    ["post"]=> 
    array(6) { 
    ["post_id"]=> 
    string(2) "52" 
    ["status"]=> 
    string(29) "This is a test status update." 
    ["user"]=> 
    string(1) "1" 
    ["time"]=> 
    string(19) "2015-02-05 19:47:42" 
    ["modified"]=> 
    string(19) "0000-00-00 00:00:00" 
    ["comment"]=> 
    array(2) { 
     [0]=> 
     array(3) { 
     ["comment_id"]=> 
     string(1) "3" 
     ["comment"]=> 
     string(22) "This is a test comment" 
     ["comment_datetime"]=> 
     string(19) "2015-02-06 08:36:15" 
     } 
     [1]=> 
     array(3) { 
     ["comment_id"]=> 
     string(1) "5" 
     ["comment"]=> 
     string(11) "sdfsdfsdfds" 
     ["comment_datetime"]=> 
     string(19) "2015-02-06 09:33:25" 
     } 
    } 
    } 
} 

我已经通过得到的数据是这样的尝试:

<?php 
    foreach($post as $data){ 
    $data['status']; 
    $data['post_id']; 
    } 
?> 

但是,当我做到这一点我得到非法串偏移错误消息。

+0

尝试在foreach循环中打印值 – john 2015-02-06 07:30:33

回答

0

您应该使用

foreach ($post['post'] as $data) 

如果要打印的数组称为$后,你可以看到这是一个嵌套数组。

1

如果您在数据

$data['post_id']; 

是不是你的数组中清楚地看,它的存在在$数据[“后”]中的数据,有阵内阵..所以你需要相应地查找数据。

为了在代码访问键和值,你可以使用

foreach($post as $key=>$value){ 
    // $key will have the keys and $value will have the corresponding values 
    } 
+0

如何定义$ key和$ value? – 2015-02-06 07:59:14

+0

$ key和values已经存在.. – 2015-02-06 08:04:00

0

试试这个代码

<?php 
    foreach($post as $data){ 
    $data['post']['status']; 
    $data['post']['post_id']; 
    } 
?> 
0

由于帖子数组是关联数组,你最好使用$帖[”后']而不是在foreach。这里是我分享的链接来解决它http://goo.gl/W7JgAQ

1

在您将数据传递到视图之前把当前($ dataset)并传递它来查看。所以,你可以通过$访问后[ 'commnents']

$this->load->view('your_view_name',current($data_set_passing)); 
0

试试这个..

<?php 
    foreach($post->result_array() as $data){ 
    $data['status']; 
    $data['post_id']; 
    } 
?> 
0

试试这个,只要你想,你会得到的结果:

foreach($posts as $data) 
    { 

     echo $data['post_id']; 
     echo $data['status']; 
     echo $data['user']; 
     echo $data['time']; 
     echo $data['modified']; 
     foreach($data['comment'] as $sub) 
      { 
       echo $sub['comment_id']; 
       echo $sub['comment']; 
       echo $sub['comment_datetime']; 
      } 
    }