【发布时间】:2016-08-25 10:00:27
【问题描述】:
我有一个 Laravel 查询返回一个列表。我需要过滤这个列表并在过滤后随机选择一个项目。
$places = getPlaces();
if ( count($places) > 0) {
$places = array_filter($places, "filter"); // 2016/08/25: see http://php.net/manual/en/function.array-filter.php
$randomPlace = $places[rand(0, count($places) - 1)];
}
这会报错:
array_filter() expects parameter 1 to be array, object give
如果我将 $places 转换为数组,则会出现错误,但我什么也得不到:
$places = getPlaces();
if ( count($places) > 0) {
$places = (array)$places;
$places = array_filter($places, "filter");
$randomPlace = $places[rand(0, count($places) - 1)];
}
当我查看count($places) 时,我看到只有一项。结果集有几个。
为了解决过滤器问题,我使用 Eloquent 的 toArray():
if ( count($places) > 0) {
$places = $places->toArray();
$places = array_filter($places, "filter");
if ( count($places) > 0) {
$randomPlace = $places[rand(0, count($places) - 1)];
}
}
这适用于filter,但我遇到了几个挑战:
我无法将 $randomPlace 作为对象访问,例如$randomPlace->名称。我必须使用数组访问,$randomPlace['name']。由于还有其他方法需要一个对象,这意味着必须更改/转换所有这些方法。
-
$places[rand(0, count($places) - 1)] 给出错误,例如:
Undefined offset: 4
除了必须更改所有方法以使用 arrays 而不是 objects(从而失去功能)之外,目前我唯一想到的其他方法是创建一个迭代 $places 的函数,并且将对象放入数组中。
有没有更好的处理方法?
谢谢。
【问题讨论】:
-
您可以使用收集方法
$places->filter('filter')或尝试仅使用array_values($places)获取值。我的猜测是array_filter保留了密钥并删除了 key=4 的项目。
标签: php arrays laravel eloquent array-filter