【问题标题】:Accessing eloquent list as an array of objects in Laravel 4在 Laravel 4 中将 eloquent 列表作为对象数组访问
【发布时间】: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,但我遇到了几个挑战:

  1. 我无法将 $randomPlace 作为对象访问,例如$randomPlace->名称。我必须使用数组访问,$randomPlace['name']。由于还有其他方法需要一个对象,这意味着必须更改/转换所有这些方法。

  2. $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


【解决方案1】:

看起来您正在处理一个集合,并且在将其转换为可以在其中使用array_filter 的数组时出错。相反,使用内置的收集方法来过滤和检索随机元素:

$randomItem = $places->filter('filter')->random();

在上面的示例中,filter() 方法的参数是过滤器函数的名称。我建议将其命名为 filter 以外的其他名称以提高可读性。 :)

【讨论】:

  • 谢谢,这很好用。学习 PHP 中的集合也很棒。不过,我注意到一件事,集合的 filter 不采用 string 作为参数,而是采用 closure
猜你喜欢
  • 1970-01-01
  • 2021-11-12
  • 2013-07-05
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 2013-10-20
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多