douyi1939 2013-02-04 17:23
浏览 195
已采纳

PHP:这是一个错误:shuffle()期望参数1是数组,给定对象?

I have an object that implements the ArrayableInterface (BTW, it's from Laravel's Eloquent ORM).

This object is $articles. So naturally, I can do this:

foreach ($articles as $article)
    echo $article->title . "<br/>";

But I can't do this:

shuffle($articles);

I get the shuffle() expects parameter 1 to be array, object given warning.

  • 写回答

2条回答 默认 最新

  • drl37530 2013-02-04 17:32
    关注

    No, it's not a bug.

    PHP 5 allows you to use foreach() to loop through objects that aren't arrays. These objects are called Iterators.

    Unfortunately, the old array-based functions, like shuffle() cannot process Iterators.

    The main reason for this is that an Iterator may not even be sortable -- for example, you can have iterators that read directly from a file or a URL, and read a new line of data each time the foreach() loop cycles. This clearly can't be sorted because it's read during the foreach() process.

    You can convert an Iterator into an array, using the cleverly named iterator_to_array() function. However, this may be a bad idea if you don't know how much data the iterator is going to process, as you may find it uses a lot of memory.

    Some iterators may provide methods within the iterator object itself for sorting or filtering the data. If so, this is a better solution than trying to sort it as an array.

    If you're working with an ORM, then this implies that your Iterator object is reading data from a DB. In this case, sorting it via the DB query (ie ORDER BY or whatever methods the ORM provides to do that) would probably be a better solution than sorting the data in PHP.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器