Lecture aléatoire des objets en PHP
Question
Comment puis-je trier un objet en PHP? J'ai essayé shuffle()
mais attend un tableau:
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
Ceci est mon code:
public function updateStatusWithoutDB() {
$this->updateProfileColors();
$items = $this->getItems();
$items = shuffle($items);
if($this->updateStatusArray($items))
return true;
return false;
}
A var_dump($items);
retourne ceci:
["180"]=>
object(stdClass)#203 (1) {
["status"]=>
string(130) "I was checking Microsoft's Visual Studio page just no…"
}
La solution
Vous ne pouvez pas trier un objet, car il n'y a pas d'ordre dans les attributs.
Cependant, vous pouvez trier une représentation de tableau d'un objet:
$arr = (array)$object;
shuffle($arr);
Autres conseils
Puisque vous utilisez des articles $ comme un tableau, soit faire $this->getItems()
retourner un tableau ou utilisez get_object_vars($items)
pour obtenir ensemble des vars de l'objet.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow