2

I have a table called "grids". Columns are id, floor, and grid.

id                 floor           grid
==========         =======       =======
1                     EG            LEFT
2                     EG            RIGHT
3                     DG            LEFT
4                     DG            RIGHT

When I get all my data with:

$data = Grid::all()

I have an array with 0 => Grid Object 1, 1 => Grid Object 2, and so on..

But how is it possible to group my Result in an array like this:

$data = array(
        'EG' => array(
            'LEFT' => Grid Object 1,
            'RIGHT' => Grid Object 2,
        )
        'DG' => array(
            'LEFT' => Grid Object 3,
            'RIGHT' => Grid Object 4,
        )
    )

Thanks in advance

2 Answers 2

3

As of present Laravel versions, you can use the groupBy function

$data = $data->groupBy('floor');

Will give you the desired array

Sign up to request clarification or add additional context in comments.

Comments

1

I think you'll have to do that manually. Meaning loop through the collection and build the new structure

$result = array();
foreach($data as $d){
    if(!isset($result[$d->floor])){
        $result[$d->floor] = array();
    }
    $result[$d->floor][$d->grid] = $d;
}

2 Comments

okay thanks. I feared it. I thought there might be a laravel eloquent function for this ...
Not as far as I know. But it's not "bad" when you have to do some things yourself.. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.