0

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++;
    }
}
Elexer
  • 153
  • 3
  • 9
  • Can't you specify the ordering in the database query? – Barmar Sep 09 '22 at 16:33
  • Nope, because i need check all Diseases where symptoms match – Elexer Sep 09 '22 at 16:38
  • What does that have to do with it? something like `Diseases::find()->orderBy(...)->localized($lang)->all()` – Barmar Sep 09 '22 at 16:40
  • Oh, you're talking about the count of matches after you explode the symptoms? You'll need to sort the array after the loop is done. – Barmar Sep 09 '22 at 16:42
  • 2
    This looks like a database design problem. You shouldn't put comma-delimited lists in the database, you should normalize. See https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad – Barmar Sep 09 '22 at 16:42
  • No problem in database design, Disease have some symptoms, stored as an array, i need check if selected symptom have in array, after i need count how much symptoms match, after i need sort highest – Elexer Sep 09 '22 at 17:14

1 Answers1

0

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

Elexer
  • 153
  • 3
  • 9