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

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 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口