mardi 8 décembre 2020

Merge two eloquent collections with identical keys

Lets say I have a collection like

{
    "object1": [
        {
            "name" xxx,
            "size" 999
        }
    ],
    "object2": [
        {
            "name": yyy,
            "size": 888,
        }
    ]
}

And I have another collection like

{
    "object2": [
        {
            "name" aaa,
            "size" 111
        }
    ],
    "object3": [
        {
            "name": bbb,
            "size": 222,
        }
    ]
}

I would like to get a collection like

{
    "object1": [
        {
            "name" xxx,
            "size" 999
        }
    ],
    "object2": [
        {
            "name": yyy,
            "size": 888,
        },
        {
            "name" aaa,
            "size" 111
        }
    ],
    "object3": [
        {
            "name": bbb,
            "size": 222,
        }
    ]
}

[MergeRecursively][1]

[1]: https://laravel.com/docs/8.x/collections#method-mergerecursive works but add encapsulates the results in an "items" array which looks like this

{
    "object1": [
        {
            "name" xxx,
            "size" 999
        }
    ],
    "object2": {
        "items": [
            {
                "name": yyy,
                "size": 888,
            },
            {
                "name" aaa,
                "size" 111
            }
        ]
    ],
    "object3": [
        {
            "name": bbb,
            "size": 222,
        }
    ]
}

Any help is appreciated! Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire