【问题标题】:Multiples arrays into one将多个数组合二为一
【发布时间】:2014-02-02 21:44:03
【问题描述】:

我有一个 SQL 查询,可以从不同的表中获取结果。我得到这样的结果:

\app\View\Followings\index.ctp (line 14)
array(
    'Following' => array(
        'id' => '1',
        'user_id' => '3',
        'follower_id' => '2'
    ),
    'Blogging' => array(
        (int) 0 => array(
            'id' => '1',
            'value' => 'What is zyzz about ?',
            'user_id' => '3',
            'created' => '2014-01-01 00:00:00'
        )
    ),
    'Photo' => array(
        (int) 0 => array(
            'id' => '3',
            'value' => 'zyzz.jpg',
            'user_id' => '3',
            'created' => '2014-02-12 00:00:00'
        ),
        (int) 1 => array(
            'id' => '2',
            'value' => 'zyzz2.jpg',
            'user_id' => '3',
            'created' => '2015-05-07 00:00:00'
        )
    )
)
\app\View\Followings\index.ctp (line 14)
array(
    'Following' => array(
        'id' => '2',
        'user_id' => '4',
        'follower_id' => '2'
    ),
    'Blogging' => array(
        (int) 0 => array(
            'id' => '3',
            'value' => 'lolpl',
            'user_id' => '4',
            'created' => '2013-12-01 00:00:00'
        ),
        (int) 1 => array(
            'id' => '2',
            'value' => 'Do you even lift brah ?',
            'user_id' => '4',
            'created' => '2015-06-18 00:00:00'
        )
    ),
    'Photo' => array()
)

我的问题是如何获得一个混合了“用户”和按 id(或按日期)排序的“值”的单个数组?谢谢。

控制器:

public function index(){

    $followings = $this->Following->find('all', array(
        'conditions' => array('Following.follower_id' => $this->Auth->user('id')),
        'recursive' => 1,
    ));


    $this->set('followings', $followings); 

}

【问题讨论】:

  • 请发布更多代码,从控制器中的代码开始,这些代码准备并执行填充这些数组的查询。
  • 我已将其添加到原始帖子中

标签: php sql arrays cakephp


【解决方案1】:

我建议首先尝试使用 CakePHP 的 find() 方法的内置选项来获得所需的结果。我不明白您将结果与用户“混合”是什么意思,但在您的发现中使用“顺序”和“组”可能会奏效。

对于 CakePHP 2.x: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html

如果你仍然不能得到你想要的结果结构,你总是可以通过迭代控制器内部的 $followings 结果来构建一个新数组,然后使用新数组而不是 with 执行 $this->set $followings。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2021-10-21
    • 2014-01-12
    • 1970-01-01
    相关资源
    最近更新 更多