0

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
        )
)
4
  • Shouldn't that be sort($weight[$cQ]);? Commented Jun 14, 2013 at 8:21
  • okay i have used sort($weight[$cQ][$post]); , still no output ! Commented Jun 14, 2013 at 8:22
  • asort($weight[$cq][$post]); ? Commented Jun 14, 2013 at 8:22
  • @user2345691 See my answer below. Commented Jun 14, 2013 at 8:33

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Cannot redeclare cmp() (previously declared
Rename it to something else. You might have a function named cmp in your code elsewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.