按另一个数组的值对数组进行排序

时间:2015-07-22 21:44:29

标签: php arrays sorting multidimensional-array

我有2个阵列。 第一:

$comment = Array ( 
    [1] => 1 
    [ 2] => 1 
    [ 3] => 8 
    [ 5] => 3 
    [ 6] => 2 
    [ 7] => 4 
         ) 

我有第二个阵列:

$item = Array ( 
[0] => Array ( [id] => 1 [title] => Neque porro quisquam est qui dolorem ) 
[1] => Array ( [id] => 2 [title] => Sed a est quis sem pellentesque luctus. ) 
[2] => Array ( [id] => 3 [title] => There is no one who loves pain itself ) 
[3] => Array ( [id] => 5 [title] => There is no one who loves pain itself ) 
[4] => Array ( [id] => 6 [title] => Sed a est quis sem pellentesque luctus. ) 
[5] => Array ( [id] => 7 [title] => Neque porro quisquam est qui dolorem ) 
) 

在数组"评论" key是数组中的id" item"。 我想排序数组" item"对于数组的值"评论"。

例如:

[2] => Array ( [id] => 3 [title] => There is no one who loves pain itself ) // value in $comment 8
[5] => Array ( [id] => 7 [title] => Neque porro quisquam est qui dolorem )       // value in $comment 4
[3] => Array ( [id] => 5 [title] => There is no one who loves pain itself ) // value in $comment 3
...

我尝试使用array_multisort进行排序,但我无法做到。 帮助解决这个问题。

1 个答案:

答案 0 :(得分:2)

试试这个

// first merge the arrays

foreach ($item as $key => $tab) {
    $item[$key]["numComment"] = $comment[$tab["id"]];
}


// then sort

usort($item, function ($t1, $t2) {
    return $t2["numComment"] - $t1["numComment"];
});

var_dump($item);