2014-11-22 74 views
-1

我有一个数组$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 
      ) 
) 

回答

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

看看这个php article此外,如果你希望你的两个数组有关系,比你能更好地把它写这样的:

array(
    array(
     name => 'Messi', 
     rank => 4, 
    ), 
    etc.. 
); 
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; 
});