SSK
SSK

Reputation: 285

Sorting array values in ascending order

I have store array value in the following variable

$weight[$cQ][$post] 

where $cQ is Index and $post is article ID , i am storing rating values in the array.

I have used sort($weight[$cQ][$post]) PHP function for ascending order. But its not ordering array values.. Is there any good solution for sorting array ascending.

Array
(
    [0] => Array
        (
            [948] => 0.0086665
        )

    [1] => Array
        (
            [934] => 0.0119
        )

    [2] => Array
        (
            [932] => 0.0176
        )

    [3] => Array
        (
            [931] => 0.0125
        )

    [4] => Array
        (
            [940] => 0.0148
        )

    [5] => Array
        (
            [930] => 0.01235
        )

    [6] => Array
        (
            [933] => 0.01715
        )

    [7] => Array
        (
            [936] => 0.0168
        )

    [8] => Array
        (
            [945] => 0.0117665
        )
)

Upvotes: 0

Views: 1550

Answers (1)

web-nomad
web-nomad

Reputation: 6003

Use this:

It assumes every array has only one element as per your example array. If it has many, modify it accordingly.

function cmp( $a, $b ) {
    $key1 = array_keys( $a ); // all array keys in first array
    $key2 = array_keys( $b ); // all array keys in second array

    if ( $a[ $key1[ 0 ] ] == $b[ $key2[ 0 ] ] ) {
        return 0;
    }
    return ( $a[ $key1[ 0 ] ] < $b[ $key2 [ 0 ] ] ) ? -1 : 1;
}

uasort($weight, 'cmp');

Hope this helps.

Upvotes: 2

Related Questions