【问题标题】:Laravel static index on Collection集合上的 Laravel 静态索引
【发布时间】:2021-03-23 01:31:27
【问题描述】:

我正在尝试对我的 web 应用中的元素进行排名。

我有这个代码:

public static function getPetPlacing($pet_id) {
    $pets = Pet::get();
    foreach ($pets as $key => $value) {
        $value->index = $key;
        if ($value->id == $pet_id) {
            return $value->index;
        }
    }
    return $pets;
}

前面的代码创建了一个 foreach 循环,在获取所有数据后,将键 index 附加到集合的每个对象中。如果条件匹配,返回元素在所有元素中的确切索引

这是 Pet::get() 结果:

[{"id":1,"pet_name":"boris"},{"id":2,"pet_name":"michael"},{"id":3,"pet_name":"john"},{"id":4,"pet_name":"snoop"}]

加上 foreach 循环和 index 键,它看起来像这样:

[{"id":1,"pet_name":"boris","index":0},{"id":2,"pet_name":"michael","index":1},{"id":3,"pet_name":"john","index":2},{"id":4,"pet_name":"snoop","index":3}]

问题来了

如果我调用函数 getPetPlacing($pet_id),它会给我这个结果:

getPetPlacing(2);
// returns 0 when it should be 1

getPetPlacing(4);
// returns 0 when it should be 3

当条件匹配时,它总是返回"index":0

如何才能在我的函数中获得所需的结果?

我尝试在我正在处理的视图中执行 foreach,但我认为循环遍历集合中的每个对象并不是提高性能的最佳方法。

你能帮帮我吗?谢谢!

【问题讨论】:

  • 这是非常昂贵的逻辑。
  • 传递$pet_id时使用了什么逻辑,$pet_id是从哪里来的?

标签: php laravel indexing collections


【解决方案1】:

Laravel 解决这个问题的方法是使用 Collection -> Search,它可以返回通过真值测试的项目的索引:

https://laravel.com/docs/8.x/collections#method-search

$pets = Pet::all();
$pets->search(function ($item, $key) {
    return $item->id == 27;
});

【讨论】:

  • 对不起,但它对我不起作用 :( 它说:类 App\Models\Pet 的对象无法转换为 int。我查看了文档并尝试失败
  • @DavidEncinaMartínez 请阅读 Laravel 关于模型和集合的文档。您不能在单个模型上运行搜索,它必须在模型集合上。另外 $item->id = 27 应该是我修复的 $item->id == 27 。
【解决方案2】:

抱歉,我没有提到订单是通过名为 GetPetScore() 的评分函数发出的,我出于私人原因将其隐藏了。该函数根据几个因素给 pet 打分,这些因素在我写的以前的集合中没有显示。无论如何,问题是这样解决的:

public static function getPetPlacing($pet_id) {
  $pets = Pet::get();
  $sorted = $pets->sortByDesc('score');
  return array_search($pet_id, array_column($sorted->toArray(), 'id'));
}

谢谢你们帮助我:D

【讨论】:

    猜你喜欢
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2019-10-11
    • 2021-09-01
    相关资源
    最近更新 更多