Reputation: 13
How can I loop through a PHP array of objects (the objects are books with title and price) and output the one whose title comes after the letter R alphabetically? Thanks
Should I create an array with alphabetic letters then merge that array with book's array (in this case bookInformation
)?
class Book {
public $title;
public $price;
public function __construct($title, $price) {
$this->title = $title;
$this->price = $price;
}
public function info() {
echo $this->title . ' is ' . $this->price . '<br>';
}
}
$bookOne = new Book("Mall", 13.95);
$bookTwo = new Book("Will", 23.99);
$bookOne->info();
$bookTwo->info();
$bookInformation = [$bookOne, $bookTwo];
Upvotes: 0
Views: 53
Reputation: 11
Use array_column Function
$Arraya = [ 'ObjA' => { 'title' => "booka", 'page' => 27, }, 'Objb' => { 'title' => "bookb", 'page' => 37, }, ];
$ArrayofArray = json_decode(json_encode($Arraya), 1);
$titles = array_column($ArrayofArray, "title");
Here $title
return array of title
Upvotes: 0
Reputation: 147266
You can use array_filter
to find all the books whose title comes after R
, then sort that list by title using usort
and then printing the first element in the sorted list:
$fBooks = array_filter($bookInformation, function ($v) { return substr($v->title, 0, 1) > 'R'; });
if (count($fBooks)) {
usort($fBooks, function ($a, $b) { return strcmp($a->title, $b->title); });
print_r($fBooks[0]);
}
else {
echo "no book found!";
}
Upvotes: 1