2
votes

I have an associative array of data, from which need to group with associative array value.

$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
        )
    )
)

Is it possible to group above array using User.id using Hash utility? Like this:

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
            )
        )
    )
)

I tried with few methods Hash::combine(), Hash::extract but couldn't achieve it. Can someone have an idea.

Thanks in advance!

2
you can make this array using foreach loop. - Md. Sahadat Hossain

2 Answers

1
votes

The following line will produce an array similar to what you need:

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

With the exception that the nested numerical index holds the number stored in App.id instead of a sequential numerical index.

This will work if App.id is unique in your result set. Alternatively, you can use Project.id as $keyPath.

Reference:

0
votes

To improve @Inigo Flores answer, you can get indexed instead of associative by setting the second parameter to null:

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