如何通过模型的一个属性对Yii2模型结果集进行分组?

时间:2016-06-21 11:36:46

标签: php arrays yii2

在我的学生中'表格,有字段' id',' student_name',' father_name',' class',这样

var_dump(Students::find()->All());

给出以下结果

array (size=284)
  0 => 
    object(frontend\models\Students)[68]
      private '_attributes' (yii\db\BaseActiveRecord) => 
        array (size=10)
          'id' => int 1
          'student_name' => string 'VATS' (length=5)
          'father_name' => string 'KARAMJEET SINGH' (length=15)
          'class' => string '1st' (length=3)

    1 => 
    object(frontend\models\Students)[68]
      private '_attributes' (yii\db\BaseActiveRecord) => 
        array (size=10)
          'id' => int 2
          'student_name' => string 'VASHISHT' (length=5)
          'father_name' => string 'PARAM KUMAR' (length=15)
          'class' => string '1st' (length=3)     

        ......................
        ......................
        ......................

我想使用'班级'作为索引的模型领域如下... 例如

1st => 
    0=> 'id' => int 1
          'student_name' => string 'VATS' (length=5)
          'father_name' => string 'KARAMJEET SINGH' (length=15)
          'class' => string '1st' (length=3)  
    1=>  array (size=10)
          'id' => int 2
          'student_name' => string 'VASHISHT' (length=5)
          'father_name' => string 'PARAM KUMAR' (length=15)
          'class' => string '1st' (length=3)     

          ......................
          ......................

我尝试了Arrayhelper::map($array,... , .. )函数,也尝试了Arrayhelper::index(..)函数。 Arrayhelper::index($array, 'field_name_to_be_used_as_index')似乎可以完成这项工作,但它只为每个班级提供了一个结果'类型。 如何以上述格式实现数组?

1 个答案:

答案 0 :(得分:3)

实现这一目标的唯一方法是循环并创建一个新数组

$original_array = Students::find()->asArray()->All();
$grouped_array = [];
foreach ($original_array as $value) {
    $grouped_array[$value['class']][] = $value;
}
var_dump($grouped_array);