对关联数组进行排序

时间:2014-11-22 12:15:54

标签: php arrays sorting associative-array

我有一个数组$array

$array =>
(
  ['name'] => (
                 "Ronaldo","Ribery","Bale","Messi"
               ),
  ['rank'] => (
                2,4,1,3
              )
)

现在如何使用DESC字段和rank对数组name进行排序 预期输出 - >

$array =>
(
  ['name'] => (
                 "Ribery","Messi","Ronaldo","Bale"
               ),
  ['rank'] => (
                4,3,2,1
              )
)

3 个答案:

答案 0 :(得分:2)

有效用于误解array_multisort()

<?php
$array = [
  'name' => ["Ronaldo","Ribery","Bale","Messi"],
  'rank' => [2,4,1,3]
];
array_multisort(
    $array['rank'], SORT_DESC, SORT_NUMERIC,
    $array['name'], SORT_ASC,  SORT_STRING
);
var_dump($array);

array(2) {
  'name' =>
  array(4) {
    [0] =>
    string(6) "Ribery"
    [1] =>
    string(5) "Messi"
    [2] =>                                                                                                                                                            
    string(7) "Ronaldo"                                                                                                                                               
    [3] =>                                                                                                                                                            
    string(4) "Bale"                                                                                                                                                  
  }                                                                                                                                                                   
  'rank' =>
  array(4) {
    [0] =>
    int(4)
    [1] =>
    int(3)
    [2] =>
    int(2)
    [3] =>
    int(1)
  }
}

答案 1 :(得分:1)

如果你希望你的两个数组有一个关系,那么查看这个php article,你可以更好地编写它:

array(
    array(
        name => 'Messi',
        rank => 4,
    ),
    etc..
);

答案 2 :(得分:0)

为什么不更改数据结构才能使用对象?

class Player {
    public $name; // would be better as private and add getters
    public $rank;

    public function __construct($name, $rank) {
        $this->name = $name;
        $this->rank = $rank;
    }
}

然后填充你的阵列(我不熟悉足球):

$players = [   // or array(...) if you are using older PHP
    new Player('Foo', 3),
    new Player('Bar', 1),
    new Player('FooBar', 2)
];

然后你可以使用常规排序:

// or a function name, if using older PHP
usort($players, function (Player $a, Player $b) { 
    if ($a->rank == $b->rank) {
        return 0;
    }
    return ($a->rank < $b->rank) ? -1 : 1;
});