Jump to content

Sort array


everisk

Recommended Posts

I have an array that looks like below. I'd like to sort it in by [ctor] in descending order. Help please~. Thanks.

 

Array
(
    [1] => Array
        (
            [url] => www.abc.com
            [stimes] => 154
            [ctor] => 19.06
        )

    [2] => Array
        (
            [url] => www.123.com
            [stimes] => 90
            [ctor] => 11.14
        )

    [3] => Array
        (
            [url] => www.xyz.com
            [stimes] => 180
            [ctor] => 22.28
        )

)

Link to comment
https://forums.phpfreaks.com/topic/93258-sort-array/
Share on other sites

it gave me

Array
(
    [0] => Array
        (
            [url] => www.123.com
            [stimes] => 90
            [ctor] => 11.14
        )

    [1] => Array
        (
            [url] => www.abc.com
            [stimes] => 154
            [ctor] => 19.06
        )

    [2] => Array
        (
            [url] => www.xyz.com
            [stimes] => 180
            [ctor] => 22.28
        )

)

 

which looks sorted to me.

 

Define "doesn't work"

Link to comment
https://forums.phpfreaks.com/topic/93258-sort-array/#findComment-482335
Share on other sites

Just re-read first post. To get DESC sort you need to reverse the sign of the value returned by the function

 

function mysort($a, $b)
{
   return $b['ctor'] - $a['ctor'];          // B-A for descending
}

usort ($myarray, 'mysort');              // use uasort() if you want to preserve array indexes

Link to comment
https://forums.phpfreaks.com/topic/93258-sort-array/#findComment-482338
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.