gpt4 book ai didi

php - 我如何在 laravel Eloquent 返回数组中使用 next() 或 current() ?

转载 作者:行者123 更新时间:2023-12-02 15:12:19 25 4
gpt4 key购买 nike

我正在构建预订系统并且正在编写递归函数。因此,我需要在 PHP 中使用 php 函数 next() 和 current()。问题是,如果我有 Eloquent 所有记录数组,它就不起作用。它适用于所有其他数组,所以我猜测内部指针未设置,但 reset() 函数也没有帮助。

问题是当我在 laravel 中调用 eloquent 模型以从这样的表中获取所有结果时:

$posts = Post::all();

然后我回显或返回(无关紧要)current($posts),我得到的结果与我返回 $posts(整个数组)时的结果相同

当我尝试调用它时:

next($posts);
return current($posts);

或者:

prev($posts);
return current($posts);

我有一个错误:

The Response content must be a string or object implementing __toString(), "boolean" given.

谁能帮我解决这个问题?如果我创建相同的数组并返回它,那么 Eloquent 数组和这个新创建的数组是相同的,但是如果我在 Eloquent 数组上使用 current,它就不起作用。感谢您的帮助。

最佳答案

$posts = Post::all(); // returns a collection

你想要

$posts = Post::all()->toArray();

然后您可以调用 current($posts)next($posts)prev($posts)end ($帖子)

但是当你有一个集合时,你总是可以使用 laravel 的集合方法,比如 first, last, each, filter , map, reduce

https://laravel.com/docs/5.4/eloquent-collections#available-methods

关于php - 我如何在 laravel Eloquent 返回数组中使用 next() 或 current() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43004449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com