PHP多数组排序

时间:2014-09-10 11:22:05

标签: php arrays sorting

我需要在数组中按一个值对多个数组进行排序。不幸的是,我无法在数据库中对此进行排序。我只能得到这样的数组。

My Array看起来像:

Array
(
    [0] => Array
        (
            [id] => 10913
            [name] => NAME 1
            [logo_img] => 28361bd6114a32daafcf150da5ee1d33.jpeg
            [has_frame] => t
            [weight] => 0
        )

    [1] => Array
        (
            [id] => 10902
            [name] => Name 2
            [logo_img] => d0642d5efeabe8b861f2f32fa17f35b3.jpeg
            [has_frame] => t
            [weight] => 4
        )

    [2] => Array
        (
            [id] => 8887
            [name] => Some name 3
            [logo_img] => 12e47533604438bf390d69218434b630.jpeg
            [has_frame] => f
            [weight] => 0
        )

    [3] => Array
        (
            [id] => 49
            [name] => Some name 4
            [logo_img] => 5971148b049c5bb0b6e402a1de1836ef.jpeg
            [has_frame] => t
            [weight] => 0
        )

    [4] => Array
        (
            [id] => 10871
            [name] => name2
            [logo_img] => 7dcc1a6058a81b4e45de5f2274025907.jpeg
            [has_frame] => t
            [weight] => 0
        )

    [5] => Array
        (
            [id] => 1880
            [name] => name 4
            [logo_img] => dc05764ea71425a4a653b81997e7d929.jpeg
            [has_frame] => f
            [weight] => 0
        )

    [6] => Array
        (
            [id] => 9678
            [name] => name 33
            [logo_img] => 8ded98244a6928d5179398fa9d3b59bc.jpeg
            [has_frame] => t
            [weight] => 5
        )

    [7] => Array
        (
            [id] => 2880
            [name] => name r
            [logo_img] => 09876329a5ac2a84e9f83923c75e780c.jpeg
            [has_frame] => f
            [weight] => 0
        )

    [8] => Array
        (
            [id] => 8265
            [name] => name 5
            [logo_img] => 487ed3c676666e380f813f5f1a9fb040.jpeg
            [has_frame] => t
            [weight] => 1
        )

)

我需要按权重元素DESC来命令这个数组。可能吗?

3 个答案:

答案 0 :(得分:2)

http://php.net/manual/en/function.sort.php

这列出了很多有关排序的信息,

如果您需要使用密钥排序,请尝试

ksort($array)

答案 1 :(得分:1)

这就是我做到的:

usort($object, 'cmp');

function cmp($a, $b)
{
    return strcmp($b['weigth'], $a['weigth']); // or -> weigth
}

答案 2 :(得分:1)

 //You can use `uasort` that has a comparison function that can be defined by user;


//if the name of the whole array is $array

//define a function 

 function compare($obj1,$obj2){
     if($obj1['weight']==$obj2['weight']){
         return 0;
     }
  return $obj1['weight']<$obj2['weight']?1:-1;

}
//the comparison operator in the function `compare` in the second return determines the order of the array elements.


 //Now call the function with your array

 uasort($array,'compare');