遍历对象数组PHP

时间:2019-08-24 03:53:30

标签: php

如何遍历PHP对象数组(这些对象是带有标题和价格的书),并输出其标题以字母R开头的字母? 谢谢

我应该创建一个包含字母的数组,然后将该数组与书籍的数组合并(在这种情况下为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 个答案:

答案 0 :(得分:1)

您可以使用array_filter查找标题在R之后的所有书籍,然后使用usort按标题对列表进行排序,然后在已排序的列表中打印第一个元素:< / p>

$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

答案 1 :(得分:0)

使用array_column 功能

$Arraya = [ 'ObjA' => { 'title' => "booka", 'page' => 27, }, 'Objb' => { 'title' => "bookb", 'page' => 37, }, ];
$ArrayofArray = json_decode(json_encode($Arraya), 1);
$titles = array_column($ArrayofArray, "title");

此处$title返回标题数组