3

如何在 PHP 中对对象进行排序?我试过shuffle()了,但这需要一个数组:

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

这是我的代码:

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

Avar_dump($items);返回:

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

2 回答 2

13

您无法对对象进行排序,因为属性中没有顺序。

但是,您可以对对象的数组表示进行排序:

$arr = (array)$object;

shuffle($arr);
于 2009-12-13T20:50:17.687 回答
0

由于您将 $items 用作数组,因此要么$this->getItems()返回一个数组,要么get_object_vars($items)用于获取对象变量的数组。

于 2009-12-14T03:58:49.593 回答