[英]How to Group a Yii2 model resultset by one of the attributes of the model?
在我的'學生'表中,有字段'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)
......................
......................
......................
我想使用模型的'class'字段作為索引,如下所示...例如
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')
似乎可以完成這項任務,但它只為每個'class'類型提供一個結果。 如何以上述格式實現數組?
實現這一目標的唯一方法是循環並創建一個新數組
$original_array = Students::find()->asArray()->All();
$grouped_array = [];
foreach ($original_array as $value) {
$grouped_array[$value['class']][] = $value;
}
var_dump($grouped_array);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.