Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle objects in PHP

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…"
    }
like image 324
streetparade Avatar asked Feb 04 '26 19:02

streetparade


1 Answers

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);
like image 143
Dan Soap Avatar answered Feb 07 '26 11:02

Dan Soap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!