A
A
Alexander Verbitsky2018-05-19 17:33:09
Yii
Alexander Verbitsky, 2018-05-19 17:33:09

How to display a model grouped by one field?

There is a table "param"
| id | param_id | value |
| 1 | 50 | Title 1 |
| 2 | 50 | Title 2 |
| 3 | 50 | Title 3 |
| 4 | 555 | Title 4 |
| 5 | 555 | Title 5 |
| 6 | 555 | Title 6 |
The command
Param::find()->asArray()->all();
outputs

Array
(
    [0] => Array
        (
            [id] => 1
            [param_id] => 50
            [value] => Название 1
        )
    [1] => Array
        (
            [id] => 2
            [param_id] => 50
            [value] => Название 2
        )
    [2] => Array
        (
            [id] => 3
            [param_id] => 50
            [value] => Название 3
        )
    [3] => Array
        (
            [id] => 4
            [param_id] => 555
            [value] => Название 4
        )
    [4] => Array
        (
            [id] => 5
            [param_id] => 555
            [value] => Название 5
        )
    [5] => Array
        (
            [id] => 6
            [param_id] => 555
            [value] => Название 6
        )
)

How can I group an array by the "param_id" field? To get an array as an output
Array
(
  [55] => Array
    (
      [0] => Array
        (
          [id] => 1
          [param_id] => 50
          [value] => Название 1
        )
      [1] => Array
        (
          [id] => 2
          [param_id] => 50
          [value] => Название 2
        )
      [2] => Array
        (
          [id] => 3
          [param_id] => 50
          [value] => Название 3
        )
      
    )
    
  [555] => Array
    (
      [0] => Array
        (
          [id] => 4
          [param_id] => 555
          [value] => Название 4
        )
      [1] => Array
        (
          [id] => 5
          [param_id] => 555
          [value] => Название 5
        )
      [2] => Array
        (
          [id] => 6
          [param_id] => 555
          [value] => Название 6
        )
    )		
)

Tried
Param::find()->groupBy('param_id')->asArray()->all();

does not work...
It is possible of course through foreach, but maybe there is another way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-05-19
@Arassir

https://www.yiiframework.com/doc/guide/2.0/en/help...
$result = ArrayHelper::index($array, null, 'param_id');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question