-1

Doing for each loop but data is out of order I have tried several variations but cannot get to sort on sub array


Running this for each loop

@foreach($record->criteria_list as $optKey=>$options)

I need to sort based on the below field and make main array ($record)sorted before the for loop

$options->total_passed_user

The other 9 examples(that i have tried) and 2 of the below are part of those examples are erroring out...page wont load.... Yes it is blade/laravel but that doesnt matter as im trying to sort this array prior to the loop and the php formatting.page loads and all code works , just order of items is out of place and trying to reorder based on $options->total_passed_user

@foreach($record->criteria_list as $optKey=>$options)

<?php
    $correctPercentage = ( $record->total_test_completed_count) ? round(($options->total_passed_user/$record->total_test_completed_count)*100):0;

etc.......

1 Answers1

0

I think, usort function will works. http://php.net/manual/en/function.usort.php


Example 1 (in PHP ≥7.0): Recomended Solution

usort($record->criteria_list, function ($a, $b) {
    return $a->total_passed_user <=> $b->total_passed_user;
});

...

@foreach($record->criteria_list as $optKey=>$options)

Example 2:

function cmp_by_total_passed_user($a, $b) {
  return $a->total_passed_user - $b->total_passed_user;
}

...

usort($record->criteria_list, "cmp_by_total_passed_user");

....

@foreach($record->criteria_list as $optKey=>$options)
mahfuz
  • 2,728
  • 20
  • 18