【问题标题】:Laravel - Sort collection with a specific order given by an array of ids [duplicate]Laravel - 使用由 id 数组给出的特定顺序对集合进行排序 [重复]
【发布时间】:2018-05-17 08:44:30
【问题描述】:

我正在努力实现以下目标:

假设我有一系列这样的产品:

$products = [{ id: 1, name: example1, price: 10 }, {id: 2, name: example2, price: 20}]

一个数组,一个id:

[0 => 2]

我想用数组对 $products 集合进行排序,这将导致在集合中首先显示 id 为 2 的产品,或者用类似的话为集合中 id 在数组上的项目提供顺序优先级,我希望你能理解我。

我没有成功的尝试(看不到任何变化):

$events = $events->sortBy(function($model) use ($ToposDestaques) {
    return array_search($model->getKey(), $ToposDestaques);
});

$events 有两个 id 为 1 和 id 为 2 的项目。

$TopoDestaques 具有以下值:

array:1 [
  0 => 2
]

【问题讨论】:

    标签: php arrays sorting laravel-5 laravel-collection


    【解决方案1】:

    我不确定您是否应该使用 sortBy 函数执行此操作,因为您按 ID 的数组排序,因此您应该迭代它而不是集合。
    这只能用 PHP std 处理:

    $products = [[ "id"=> 1, "name"=> "example1", "price"=> 10 ], [ "id"=> 2, "name"=> "example2", "price"=> 20 ],  [ "id"=> 3, "name"=> "example3", "price"=> 30 ]];
    $sortByArr = [3, 2];
    
    $sortedArray = array_reduce($sortByArr, function($array, $index) use (&$products) {
        $productIndex = array_search($index, array_column($products, "id"));
        $array[] = $products[$productIndex];
        unset($products[$productIndex]);
        return $array;
    }, []);
    
    var_dump(array_merge($sortedArray, $products));
    

    【讨论】:

    • 它不起作用,它会产生单个项目数组,我不想要那个,我想要相同的集合,但按 ids 数组重新排序。
    • 我没有写它,因为您可以通过多种方式进行操作,并且您需要选择至少会花费您的一种。我编辑了我的答案以提出一种方法来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 2021-03-13
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多