Shuffle objects in PHP

你。 提交于 2020-02-24 11:45:33

问题


How can I sort an object in PHP? I tried shuffle() but that expects an array:

Warning: shuffle() expects parameter 1 to be array, 
object given in /var/www/index.php on line 366

Warning: Invalid argument supplied for foreach() in /var/www/index.php on line 334

This is my code:

public function updateStatusWithoutDB() {
    $this->updateProfileColors();
    $items = $this->getItems();
    $items = shuffle($items);
    if($this->updateStatusArray($items))
        return true;
    return false;
}

A var_dump($items); returns this:

["180"]=>
    object(stdClass)#203 (1) {
      ["status"]=>
      string(130) "I was checking Microsoft's Visual Studio page just no…"
    }

回答1:


You cannot sort an object, since there is no order in the attributes.

However, you can sort an array representation of an object:

$arr = (array)$object;

shuffle($arr);



回答2:


Since you are using $items as an array, either make $this->getItems() return an array or use get_object_vars($items) to get array of object's vars.



来源:https://stackoverflow.com/questions/1897690/shuffle-objects-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!