【问题标题】:Is there a way to order items that are filtered in a Laravel Collection?有没有办法订购在 Laravel 集合中过滤的项目?
【发布时间】:2014-12-31 00:46:45
【问题描述】:

我有以下过滤代码:

$cards->filter(function($card) {
    if(str_contains($card->text, 'white') || str_contains($card->text, 'blue') || str_contains($card->text, 'black') || str_contains($card->text, 'red') || str_contains($card->text, 'green')) {
        return true;
    }
});

我想按白色、蓝色、黑色、红色、绿色的顺序获得结果。我怎样才能使结果按这个顺序排列?

样本卡数据:

stdClass Object
(
    [text] => Flowers are white.
)

【问题讨论】:

  • strpos 将返回 0 如果字符串位于该干草堆的开头。虚假,它会导致你的filter 过滤掉它们。
  • 这个过滤器工作正常。只是订单需要改变。
  • 哦,我重读了你说的话。你有什么建议呢?
  • 它没有。你能给我们展示一个集合中的示例数组吗?
  • 改用 Laravel 的 str_contains

标签: php laravel collections


【解决方案1】:
$colors = ['white', 'blue', 'black', 'red', 'green'];

$cards = $cards->filter(function($card) use ($colors)
{
    return str_contains($card->text, $colors);
})
->sortBy(function($card) use ($colors)
{
    foreach ($colors as $index => $color)
    {
        if (str_contains($card->text, $color))
        {
            return $index;
        }
    }
})
->values();

【讨论】:

  • 据我所知str_contains 甚至需要一排针,所以您可以将其缩短为return str_contains($card->text, $order)
  • @JosephSilber:你太棒了。
  • @JosephSilber:有没有办法在按颜色排序之前也按字符串长度排序?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多