访问cakephp中的数组值

时间:2013-12-04 04:23:47

标签: cakephp

我需要从下面的数组结构访问数组元素。我需要访问NewsFeedComment数组。我正在尝试这样做,但是它给了我错误未定义索引:注释

如何访问NewsFeedComment数组中的元素

In Controller:
$this->set('newsfeed',$this->paginate('NewsFeed',$newsfeed));

In view:

<?php foreach ($newsfeeds $newsfeed): ?>
<div class="news_reply_display">
<?php echo $newsfeed['NewsFeedComment'][0]['comments'] ?>
</div>
<?php endforeach; ?>


array(
(int) 0 => array(
    'NewsFeed' => array(
        'id' => '2',
        'title' => 'Best Restaurant',
        'group_id' => '1',
        'posted_message' => 'message.',
        'user_id' => '11',
        'created' => '2013-12-03 09:35:02',
        'status' => 'A'
    ),
    'Group' => array(
        'id' => '1',
        'group_name' => 'My group',
        'created_user' => '1',
        'created_date' => '2013-04-24 15:31:09',
        'privacy' => '0',
        'membership' => '0',
        'description' => 'desc'
    ),

    'NewsFeedComment' => array(
        (int) 0 => array(
            'id' => '1',
            'news_feed_id' => '2',
            'comments' => 'comment1',

            'status' => 'A'
        ),
        (int) 1 => array(
            'id' => '2',
            'news_feed_id' => '2',
            'comments' => 'comment2',

            'status' => 'A'
        ),
        (int) 2 => array(
            'id' => '3',
            'news_feed_id' => '2',
            'comments' => 'comment3',

            'status' => 'A'
        )
    )
),
(int) 1 => array(
    'NewsFeed' => array(
        'id' => '1',
        'title' => 'Test Subject',
        'group_id' => '1',
        'posted_message' => 'description.',
        'user_id' => '1',
        'created' => '2013-12-03 08:25:12',
        'status' => 'A'
    ),
    'Group' => array(
        'id' => '1',
        'group_name' => 'secondgroup',
        'title' => 'Second Grouups',
        'group_slug' => 'secgroup',
        'created_user' => '1',
        'created_date' => '2013-04-24 15:31:09',
        'privacy' => '0',
        'membership' => '0',
        'description' => 'desc'
    ),

    'NewsFeedComment' => array()
)

2 个答案:

答案 0 :(得分:0)

该指数不存在。在这种特殊情况下,你必须使用$ newsfeed [0] ['NewsFeedComment'] ['comments']。

现在,如果您想从$ newsfeed中提取所有“NewsFeedComent”数组,那么您可以使用Hash::extract

$newsFeedComments = Hash::extract($users, '{n}.NewsFeedComment');
debug($newsFeedComments);

答案 1 :(得分:0)

foreach($newsfeeds as $newsfeed){ 
   foreach($newsfeed['NewsFeedComment'] as $NewsFeedCommentData){

       echo $NewsFeedCommentData['comments'];

   }
 }

使用上面的代码,您将获得与数组$ newsfeeds

的每个索引相对应的注释