Home > Software design >  Sorting foreach loop by highest number
Sorting foreach loop by highest number

Time:09-12

I need sort foreach by count from highest, for example count 5 first, count 4 secod, etc...

$i = 0;
$diseases = Diseases::find()->localized($lang)->all();
foreach ($diseases as $disease) {
    $selected_symptoms_array = explode(',', $symptoms);
    $symptoms_array = explode(',', $disease->symptoms_id);
    if (count(array_intersect($selected_symptoms_array, $symptoms_array)) > 0){
        $data[$i]['translation']['title'] = $disease->title;
        $data[$i]['id'] = $disease->id;
        $data[$i]['count'] = count(array_intersect($selected_symptoms_array, $symptoms_array));
        $i  ;
    }
}

CodePudding user response:

Solution:

ArrayHelper::multisort($data, function ($item) {
    return isset($item['count']) ? $item['count'] : $item['id'];
}, SORT_DESC);

Updated: this is a standard function from the yii2 documentation. it sorts the array by given keys after foreach

  • Related