【问题标题】:CakePHP Hash Combine group array by valueCakePHP Hash 按值组合组数组
【发布时间】:2016-02-20 06:04:09
【问题描述】:

我有一个关联的数据数组,需要用关联数组值分组。

$data = Array
(
    [0] => Array
    (
        [App] => Array
        (
            [id] => 12
            [user_id] => 121
            [skill] => Baking Cakes
        )
        [Project] => Array
        (
            [id] => 12
            [name] => P1
        )
        [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    ),
    [1] => Array
    (
        [App] => Array
        (
            [id] => 15
            [user_id] => 121
            [skill] => Baking Cakes
        )
        [Project] => Array
        (
            [id] => 13
            [name] => P2
        )
        [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    )
)

是否可以使用 Hash 实用程序使用 User.id 对上述数组进行分组? 像这样:

Array
(
    [121] = Array
    (
        [0] => Array
        (
            [App] => Array
            (
                [id] => 12
                [user_id] => 121
                [skill] => Baking Cakes
            )
            [Project] => Array
            (
                [id] => 12
                [name] => P1
            )
            [User] => Array
            (
                [id] => 121
                [name] => Gwoo the Kungwoo
                [created] => 2007-05-01 10:31:01
            )
        ),
        [1] => Array
        (
            [App] => Array
            (
                [id] => 15
                [user_id] => 121
                [skill] => Baking Cakes
            )
            [Project] => Array
            (
                [id] => 13
                [name] => P2
            )
            [User] => Array
            (
                [id] => 121
                [name] => Gwoo the Kungwoo
                [created] => 2007-05-01 10:31:01
            )
        )
    )
)

我尝试了几种方法 Hash::combine(), Hash::extract 但无法实现。 谁能给个主意。

提前致谢!

【问题讨论】:

  • 你可以使用foreach循环来创建这个数组。

标签: php arrays cakephp grouping


【解决方案1】:

以下行将生成一个类似于您需要的数组:

$result=Hash::combine($data, '{n}.App.id', '{n}','{n}.User.id');

除了嵌套数字索引保存存储在App.id 中的数字而不是顺序数字索引。

如果App.id 在您的结果集中是唯一的,这将起作用。或者,您可以将Project.id 用作$keyPath

参考:

【讨论】:

  • 你只有一步之遥 - 如何让它使用索引而不是关联?
【解决方案2】:

为了改进@Inigo Flores 的答案,您可以通过将第二个参数设置为 null 来获得索引而不是关联:

$result=Hash::combine($data, null, '{n}','{n}.User.id');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-22
    • 2017-06-07
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 2022-11-17
    • 2015-08-24
    相关资源
    最近更新 更多