0

Possible Duplicate:
php sort array by sub-value

I have a multidimensional array like the following:

Array => (
    [0] => Array(
        [a] => abcd,
        [b] => 22
    ),
    [1] => Array(
        [a] => defg,
        [b] => 12
    ),
    .....
)

I want to sort this array by the value of the index b in the internal arrays. If I want to sort it descending then the example is now in okay. But if I want to sort in ascending way the expected output will be:

    Array => (
    [0] => Array(
        [a] => defg,
        [b] => 12
    ),
    [1] => Array(
        [a] => abcd,
        [b] => 22
    ),
    .....
)

Thanks!

0

1 Answer 1

1

You can try this function:

bool uasort ( array &$array , callback $cmp_function )

here is my code:

$arr = array(
    0 => array('a' => 'abcd','b' => 22),
        1 => array('a' => 'defg','b' => 12),
    2 => array('a' => 'dfdf','b' => 32)
);

uasort($arr,'mul_sort');

function mul_sort($a,$b)
{
    if($a['b'] > $b['b'])

        return 1;//here,if you return -1,return 1 below,the result will be descending 

    if($a['b'] < $b['b'])

        return -1;

    if($a['b'] == $b['b'])

        return 0;
}

print_r($arr);
output:
---------- PHP ----------
Array
(
    [1] => Array
        (
            [a] => defg
            [b] => 12
        )

    [0] => Array
        (
            [a] => abcd
            [b] => 22
        )

    [2] => Array
        (
            [a] => dfdf
            [b] => 32
        )

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

1 Comment

Welcome to SO ! If you want to format your code, you can use 4 spaces or encapsule your line with `

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.