I ask for help, I can not think of it!

I have a table in the database.

Here is a structure. Each record has a param field, there is a number from 1 to 4, based on this number I need to sort all the records by 4. A total of 26 items in the table:

 [ 0 => app\models\Paramdoor#1 ( [yii\db\BaseActiveRecord:_attributes] => [ 'id' => 1 'name' => 'Стандарт' 'price' => '' 'param' => 1 'content' => 'Коробочный брус' 'disabled' => 1 ] ) 1 => app\models\Paramdoor#2 ( [yii\db\BaseActiveRecord:_attributes] => [ 'id' => 2 'name' => '1 комплект' 'price' => '601 грн' 'param' => 1 'content' => 'Коробочный брус Стандарт' 'disabled' => 0 ] ) 

I create 4 empty arrays:

 $arr1 = array(); $arr2 = array(); $arr3 = array(); $arr4 = array(); 

As I understand through foreach I run a multidimensional array:

 foreach ($params as $param=>$row) { if($row[param]==1){ $arr1[]=$row; } else if($row[param]==2){ $arr2[]=$row; } else if($row[param]==3){ $arr3[]=$row; } else if($row[param]==4){ $arr4[]=$row; } } 

And so I get 4 different arrays for each <select> .

What is of interest - is there a more elegant way?

  • and what prevents to make one hash of arrays? $paramArr[$row[$param]][]=$row - zb '
  • as a sloupok: such a construction is a typical switch, if else if is not needed here. - etki
  • And I would advise you to forget about the ifelse construction in php, for that there is a switch! - ashalbulk
  • Well, do not forget completely))) For cases like this: x == 1, x == 2, etc. Really switch more suitable. - artoodetoo
  • @eicto, but if you really want separate arrays, ${"arr" . $row["param"]}[] = $row; ${"arr" . $row["param"]}[] = $row; - Serge Seredenko

3 answers 3

This seems to suit you:

 list($arr1, $arr2, $arr3, $arr4) = $params; 

    Try this:

     foreach($params as $item) { $arrName = "arr".intval($item['param']); ${$arrName}[] = $item; } 

      Or so)

        foreach($params as $item) { $arr[$item['param']][] = $item; }