元素后的Laravel切片集合 [英] Laravel slice collection after an element

查看:165
本文介绍了元素后的Laravel切片集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个模型,它将命名为客户 客户有

So I have this Model, which am going to name Clients Clients has

  1. id int PK
  2. 名称varchar
  3. 电话信息
  4. 城市varchar
  5. 活动tinyint

我选择了这种方式来获取按城市分组的电话号码

I chose this way to get the phone numbers grouped by cities

return Clients::select('name','phone','city')->selectSub('lpad(phone,1,'0'))->where('active',1)->groupBy('city')->paginate(10);

如果我具有以下输出,我想将集合切成某个客户端的子集合:

I want to slice the collection to a sub collection from a certain client, in other terms, if I have the following output :

  1. 约翰0123456巴黎
  2. 杰克0255664蒙特利尔
  3. 简0165656伦敦
  4. 弗雷德0164465多伦多
  5. 琼0556494巴塞罗那
  6. Pete 0656897罗姆人

如何继续对该集合进行切片,以获取最后2个项目(从我选择的条目中获取其他4个项目,6个项目...换句话说) 我知道Laravel有一个用于集合的slice方法,但是如何动态地做到这一点呢? 谢谢.

How can I proceed to slice this collection so as to get the 2 last items (4 last items, 6 items ... in other terms from an entry I select) I know Laravel has a slice method for collections, but how to do that dynamically ? Thank you.

推荐答案

$records = Clients::select('name','phone','city')->selectSub('lpad(phone,1,'0'))->where('active',1)->groupBy('city')->paginate(10);

假设$ name ="Jane"

Assuming $name = "Jane"

$value = collect($records)->filter(function($value) use ($name) {
    return $value->name === $name;
})->keys()->first();

此处$ value将保存Jane的索引.

Here $value will hold the index of Jane.

现在您可以通过以下方式实现切片

Now you can achieve the slicing by

$records = collect($records)->slice($value, 2)->all();

但是有一个副作用,如果找不到名称,您将获得$ value为空值.在处理切片之前,请检查$ value是否为空.

But there is one side effect, if the name isn't found, you will get $value as null. Check whether $value is null or not before processing slicing.

这篇关于元素后的Laravel切片集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆