Set :: extract Cakephp更改返回数组的格式

时间:2015-02-13 01:06:20

标签: php arrays cakephp

我是新蛋糕,所以请耐心等待。 我有这个数组

Array
(
[0] => Array
    (
        [CoursesLessons] => Array
            (
                [id] => 108
                [course_id] => 88
                [lesson_id] => 6
                [deleted] => 
            )

        [UserLessonsCompleted] => Array
            (
                [0] => Array
                    (
                        [id] => 2
                        [courses_lessons_id] => 108
                        [user_id] => 75
                        [created] => 2015-01-27 14:04:31
                        [modified] => 0000-00-00 00:00:00
                        [completed_at] => 2015-02-03 14:04:45
                        [homework_downloaded_at] => 0000-00-00 00:00:00
                        [deleted] => 
                    )

            )

    )

 //and so on

我想提取UserLessonsCompleted completed at。 我想做的是:

$stringOfIdsCompleted =  Set::extract($coursesLessons, '{n}.UserLessonsCompleted.{n}.completed_at');

我的问题是返回的数组是:

Array
(
 [0] => Array
    (
        [0] => 2015-02-03 14:04:45
    )

[1] => Array
    (
        [0] => 2015-02-06 15:08:01
    )
//and so on

虽然我想要的东西:

 Array
 (
 [0] => Array
    (
        [completed_at] => 2015-02-03 14:04:45
    )

[1] => Array
    (
        [completed_at] => 2015-02-06 15:08:01
    )

有关如何实现这一目标的任何帮助?提前谢谢你的帮助

这是我如何检索我的数据:

$coursesLessons = $this->CoursesLessons->find('all', array(
        'conditions' => array(
            'CoursesLessons.course_id' => $courseId,
        ),
        'contain' => array(
            'UserLessonsCompleted' => array(
                'conditions' => array(
                    'UserLessonsCompleted.user_id' => $userId,
                ),
            ), 
        )
    ));

2 个答案:

答案 0 :(得分:2)

在find方法中添加字段属性,例如:

$coursesLessons = $this->CoursesLessons->find('all', array(
    'conditions' => array(
        'CoursesLessons.course_id' => $courseId,
    ),
    'contain' => array(
        'UserLessonsCompleted' => array(
            'fields' => array('UserLessonsCompleted.created_at'),
            'conditions' => array(
                'UserLessonsCompleted.user_id' => $userId,
            ),
        ), 
    )
));

然后提取:

$stringOfIdsCompleted =  Set::extract($coursesLessons, '{n}.UserLessonsCompleted');

答案 1 :(得分:0)

执行此操作的最佳方法是使用fieldscontain选项在控制器/模型的初始查找中处理它,如下所示:

$this->CoursesLesson->find('all', 
    array('contain' => array('UserLessonsCompleted.created_at'))
);

您需要确保附加了“可包含”行为(我将其连接到我的AppModel,因为我一直使用它。)

如果您无法解决此问题,请发布您的控制器代码,我将能够为您提供更加量身定制的答案:)