-1

I have done a code in foreach :

foreach ($queries as $record) {
    $total[] = $record->TotalTrans;
}

and from this record I wanted to determine top 5 results integer.

Example of the results are :

stdClass Object
(
    [Transactions] => A
    [TotalTrans] => 2
)
stdClass Object
(
    [Transactions] => B
    [TotalTrans] => 95
)
stdClass Object
(
    [Transactions] => C
    [TotalTrans] => 5
)
stdClass Object
(
    [Transactions] => D
    [TotalTrans] => 12
)
stdClass Object
(
    [Transactions] => E
    [TotalTrans] => 4
)

is there a way to sort it in the foreach? thank you

Hamza Zafeer
  • 2,052
  • 12
  • 27
  • 34
Boby
  • 65
  • 1
  • 1
  • 10

1 Answers1

3

Use usort to sort your $queries array:

usort
(
    $queries,
    function( $a, $b )
    {
        return $b->TotalTrans > $a->TotalTrans;
    }
);

usort sort an array by values using a user-defined comparison function: in your case, simply comparing ->TotalTrans values.

Now you array is:

Array
(
    [0] => stdClass Object
        (
            [Transactions] => B
            [TotalTrans] => 95
        )
    [1] => stdClass Object
        (
            [Transactions] => D
            [TotalTrans] => 12
        )
    [2] => stdClass Object
        (
            [Transactions] => C
            [TotalTrans] => 5
        )
    [3] => stdClass Object
        (
            [Transactions] => E
            [TotalTrans] => 4
        )
    [4] => stdClass Object
        (
            [Transactions] => A
            [TotalTrans] => 2
        )
)

To retrieve only top 5 rows:

$topFive = array_slice( $queries, 0, 5 );

Edit:

With your foreach() loop, you can proceed in this way:

foreach ($queries as $record)
{
    $total[] = $record->TotalTrans;
}

rsort( $total );
$topFive = array_slice( $total, 0, 5 );

rsort() is a function to sort an array by value in reverse order.


fusion3k
  • 11,012
  • 4
  • 21
  • 42