Group arrays with same index value

Asked

Viewed 589 times

1

I have the following array:

Array
(
    [0] => Array
        (
            [id] => 6
            [projeto_id] => 5
            [etapa_num] => 1
            [tarefa] => teste 1 
            [status] => 0
        )

    [1] => Array
        (
            [id] => 7
            [projeto_id] => 5
            [etapa_num] => 1
            [tarefa] => teste 2
            [status] => 0
        )

    [2] => Array
        (
            [id] => 8
            [projeto_id] => 5
            [etapa_num] => 2
            [tarefa] => teste 3
            [status] => 0
        )

)

How can I group arrays that have the same index value? for example: in the above code the arrays that have the index value etapa_num = 1, would be grouped in a "parent array".

  • You want, in short, to be ordered by key etapa_num?

  • That, that they are grouped in a "parent array", that would group these two arrays.

1 answer

3


Just group them together by checking a loop:

$etapas = [];
foreach($array as $key => $value) {
    $etapas[$value['etapa_num']][] = $value;
}

See working on ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.