php - how to find a specific objet in a liste of object (other way than a loop) -
i know if possible retrieve object list through id (or other way). far have loop , test each object see if correct one.
exemple
here exemple retrieve dbb liste of object picture (this list pictures).
step_1 => determining best picture id depending on attribut scorelike. highest scorelike picture best picture)
step_2 => want set attribut bestpicture yes picture id equal value of variable $id_of_best_picture, otherwise should set no.
// step_1 - determining best picture id // ---------------------------------------- $bestscorelike = o; foreach($pictures $picture) { $scorelike = $picture->getscorelike(); if($scorelike > $bestscorelike) { $bestscorelike = $scorelike; $id_of_bestpicture = $picture->getid(); } } // step_2 - having loop find object again // ------------------------------------------------------ foreach($pictures $picture) { if($picture->getid() == $id_of_bestpicture) { $picture->setbestpicture('yes'); } else { $picture->setbestpicture('no'); } }
if want set "yes" 1 of picture pictures array, should use code this;
$bestscorelike = 0; $bestpictureobject = null; foreach($pictures $picture) { $scorelike = $picture->getscorelike(); if($scorelike > $bestscorelike) { /** * in $bestpictureobject exists picture scorelike less current $picture */ if (!is_null($bestpictureobject)) { $bestpictureobject->setbestpicture('no'); } $bestscorelike = $picture->getscorelike(); $bestpictureobject = $picture; } else { $picture->setbestpicture('no'); } } $bestpictureobject->setbestpicture('yes');
you can create list keys equals $object->id
, have access $pictures[$best_picture_id]
.
Comments
Post a Comment