排序数组并保持键的值

时间:2013-04-02 10:52:16

标签: php arrays sorting

我有一个如下所示的数组:

Array
(
    [team1] => Array
        (
            [points] => 10
            [players] => Array
                (
                     ...
                )
        )

    [team2] => Array
        (
            [points] => 23
            [players] => Array
                (
                     ...
                )
        )

    ... many more teams
)

我希望按照每支球队的得分数对球队进行排序。我试过这个:

function sort_by_points($a,$b)
{
    if ($a['points']==$b['points']) return 0;
        return ($a['points']<$b['points'])?1:-1;
}

usort($this->wordswithdata, "sortbycount");

但是这种方法会覆盖包含团队名称的键并返回:

Array
(
    [0] => Array
        (
            [points] => 23
            [players] => Array
                (
                     ...
                )
        )

    [1] => Array
        (
            [points] => 10
            [players] => Array
                (
                     ...
                )
        )

    etc...
)

有没有办法对数组进行排序而不会将团队名称覆盖为数组键?

5 个答案:

答案 0 :(得分:22)

使用uasort函数,该函数应保持key =&gt;价值协会完好无损。

(旁注:你可以return $a['points'] - $b['points']代替ifs)

答案 1 :(得分:13)

您可以使用uasort

uasort($array, function($a, $b) {
    return $a['points'] - $b['points'];
});
  

此函数使用用户定义的比较函数对数组进行排序,使数组索引与它们关联的数组元素保持相关性

答案 2 :(得分:0)

U可以像这样按其值对关联数组进行排序

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

function Ascending($a, $b) {   
    if ($a == $b) {        
        return 0;
    }   
        return ($a < $b) ? -1 : 1; 
}  

function Descending($a, $b) {   
    if ($a == $b) {        
        return 0;
    }   
        return ($a > $b) ? -1 : 1; 
}  


echo "Ascending order" ;
uasort($age,"Ascending");
print_r($age);


echo "</br>Descending order" ;
uasort($age,"Descending");
print_r($age);

答案 3 :(得分:0)

its working fine i giving example
that array need sort
$sumarray=array [▼
  484 => 54.7875
  486 => 53.5375
  487 => 52.9125
  488 => 52.2875
  493 => 54.7875
]

$original=$sumarray;

 $svalue=array_values($sumarray);
  rsort($svalue);
  $sorted=array();
  foreach ($svalue as $key => $value) {
   $kk=array_search($value,$sumarray);
  $sorted[$kk]=$value;
  unset($sumarray[$kk]);

    }
  print_r($original);
    print_r($svalue);
  print_r($sorted);
             //out put
  array:5 [▼
  484 => 54.7875
  486 => 53.5375
  487 => 52.9125
  488 => 52.2875
  493 => 54.7875
]
array:5 [▼
  0 => 54.7875
  1 => 54.7875
  2 => 53.5375
  3 => 52.9125
  4 => 52.2875
]
array:5 [▼
  484 => 54.7875
  493 => 54.7875
  486 => 53.5375
  487 => 52.9125
  488 => 52.2875
]

答案 4 :(得分:-1)

试试这段代码希望它能运作。

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($your_array,"points");