Sunday, May 21, 2017

Laravel, how to group a collection by a count

How can I group a collection using a number. So I made a method that accepts a number then use that number to group the returned collection, so if I pass in a 4 it will group by 4. Below is the original structure of data.

{
    'A': [{
        id: 1, 
        id: 2,
        id: 3,
        id: 4,
        id: 5,
        id: 6,
        id: 7
    }],
    'B': [{
        id: 1,
        id: 2,
        id: 3
    }],
    'C': [{
        id: 1,
        id: 2,
        id: 3,
        id: 4
    }]
}

Now I want it to format the data this way.

{
    'A': [{
        1: [{
            id: 1, 
            id: 2,
            id: 3,
            id: 4
        }],
        2: [{
            id: 5,
            id: 6,
            id: 7
        }]
    }],
    'B': [{
        1: {
            id: 1,
            id: 2,
            id: 3
        }
    }],
    'C': [{
        1: [{
            id: 1,
            id: 2,
            id: 3,
            id: 4
        }]
    }]
}

I'm really having a hard time solving this in laravel. Btw im using 5.4 version. Any help would be much appreciated, thanks in advance!



via PenAndPapers

Advertisement