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



我有两个数组。第一:

$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 ) 
) 

在数组"comment"键中,它是数组"item"中的id。我想排序数组"item"为数组"comment"的值。

例如:

[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排序,但我不能这样做。

try this

// 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);

相关内容

  • 没有找到相关文章

最新更新