0

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];

2 Answers 2

1

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!";
}

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

You can use array_column directly on an array of objects. 3v4l.org/3ZXGA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.