如何从数组中一次检索 3 个数据?
PHP 中是否有更好的方法以三个一组的方式访问该数组?
假设我的数组是一个逗号分隔的字符串,例如:
("Thora","Birch","Herself","Franklin Delano","Roosevelt","Himself (archive footage)","Martin Luther","King","Himself (archive footage) (uncredited)")
虽然数组最终可能会更大,但每个数组都会有所不同,但仍处于三个逻辑组中(名字、姓氏、角色)。
我想要完成的是以三组为一组循环遍历数组,以便第一条记录具有 firstname[0]=>"Thora"、lastname[0]=>"Birch" 和 role [0]=>“Herself”。
我只习惯于foreach
循环,但没有看到像“for every 3”这样的额外参数,所以也许有人可以解释一下?
Is there a better way in PHP to access this array in groups of three?
Let's say my array is a comma separated string like:
("Thora","Birch","Herself","Franklin Delano","Roosevelt","Himself (archive footage)","Martin Luther","King","Himself (archive footage) (uncredited)")
Although the array can end up being much larger, each one will be different but still in logical groups of three (firstname, lastname, role).
What I'm trying to accomplish is looping through the array in groups of three, so that the first record would have firstname[0]=>"Thora", lastname[0]=>"Birch" and role[0]=>"Herself".
I'm only used to foreach
loops but don't see an extra parameter like "for each 3" so maybe someone can shed some light?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
PHP 有一个名为 array_chunk 的函数专门用于此任务。
试试这个:
请注意,最后一个块的大小可能不是 3,因此如果您不能保证数组的长度始终是 3 的倍数,则应该检查键 1 和 2 是否使用 isset 设置。
PHP has a function called array_chunk designed for this task.
Try this:
Note that the last chunk might not be of size 3, so you should check that keys 1 and 2 are set with isset, if you can't guarantee that your array is always a multiple of 3 in length.
您可以使用
for
循环来实现此目的,假设您的“people”数组的长度为3n
。You can use a
for
-loop for this, assuming your 'people' array has a length of3n
.怎么样
伪代码
How about
Pseudo code
或者,如果您使用 PHP >= 5.3:
Alternatively, if you use PHP >= 5.3: