【发布时间】: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