开发者

Shuffle objects in PHP

开发者 https://www.devze.com 2022-12-14 09:31 出处:网络
How can I sort an object in PHP? I tried shuffle() but that expects an array: Warning: shuffle() expects parameter 1 to be array,

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开发者_StackOverflow社区_dump($items); returns this:

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


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);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号