如何从数组中回显东西$ actsAs = array('Containable');

时间:2012-09-11 17:52:13

标签: php cakephp cakephp-2.0

我已阅读CakeBook关于可包含数组的指南。

class Post extends AppModel {
    public $actsAs = array('Containable');

结果是:

array(
    (int) 0 => array(
        'Post' => array(
            'id' => '1',
            'title' => 'This is the first post',
            'slug' => 'this-is-the-first-post',
            'body' => 'body body 111body body 111body body 111body body 111body body 111body body 111body body 111',
            'image_id' => '0',
            'language' => 'sv',
            'translation_id' => '0',
            'created' => '2012-09-03 17:45:57',
            'modified' => '2012-09-03 19:12:21'
        ),
        'Image' => array(
            'id' => null,
            'name' => null,
            'url' => null,
            'alt' => null,
            'description' => null
        ),
        'Asset' => array(),
        'Readmore' => array(),
        'Reference' => array(),
        'Category' => array(),
        'Course' => array(),
        'Tag' => array(),
        'User' => array(
            (int) 0 => array(
                'password' => '*****',
                'id' => '2',
                'username' => 'test0',
                'fullname' => 'Test Test',
                'url' => '',
                'email' => '',
                'role' => 'admin',
                'phone' => '+',
                'created' => '2012-09-03 17:44:22',
                'PostsUser' => array(
                    'id' => '1',
                    'post_id' => '1',
                    'user_id' => '2'
                )
            ),
            (int) 1 => array(
                'password' => '*****',
                'id' => '1',
                'username' => 'test1',
                'fullname' => 'Frank',
                'url' => '',
                'email' => '',
                'role' => 'admin',
                'phone' => '',
                'created' => '2012-09-03 17:41:25',
                'PostsUser' => array(
                    'id' => '3',
                    'post_id' => '1',
                    'user_id' => '1'
                )
            )
        )
    ),

但它不能打印出阵列的特定部分。所以,如果我在Post的索引视图中,我写道:

echo h($post['Post']['title']);

一切都很好,但是当我尝试时:

echo h($post['User']['fullname']); 

它不起作用。我明白了这一点,当我在帖子和用户之间有一个很好的和belgosto关系时,我必须遍历用户。

那么如何打印与帖子相关的所有用户?

2 个答案:

答案 0 :(得分:2)

欢迎使用Stack Overflow!

$post['User']是一组用户,因此,每个用户都有一个索引,例如,要获取test0´s全名,您需要执行以下操作:

echo h($post['User'][0]['fullname']);

尝试按以显示所有用户fullname:

<?php
foreach($post['User'] as $user) { 
    echo h($user['fullname']);
});

答案 1 :(得分:1)

谢谢!我找到了解决方案。我有点粗心,我尝试了一个手动解决方案之前,并为该模型添加了PostUser模型和控制器。删除它们,一切正常。蛋糕魔术再次起作用。