LoginSignup
3
3

More than 5 years have passed since last update.

【PHP】Objectの配列から指定したキーが最小である要素を取得する方法

Last updated at Posted at 2015-07-29

 Objectの配列から指定したキーが最小である要素を取得する

例えば以下のようなBookというClassがある

book.php
<?php
class Book {
    private $name;
    private $price;

    function __construct($name, $price) {
        $this->name  = $name;
        $this->price = $price;
    }
    public function getPrice() {
        return $this->price;
    }
}

BookClassの配列からpriceが最小のオブジェクトを取得したい

index.php
<?php
$book1 = new Book("やさしいJava", 2000);
$book2 = new Book("やさしいPHP", 1000);
$book3 = new Book("やさしいRuby", 3000);

$bookList = array( $book1,  $book2,  $book3);

コード例

以下のように単純にループすることで取得できる

index.php
<?php
$book1 = new Book("やさしいJava", 2000);
$book2 = new Book("やさしいPHP", 1000);
$book3 = new Book("やさしいRuby", 3000);

$bookList = array( $book1,  $book2,  $book3);

$result = $bookList[0];
foreach($bookList as $book) {
    if($result->getPrice() > $book->getPrice()) {
        $result = $book;     
    }
}

var_dump($result);

または、usortという関数を使用すると、ユーザー定義でソートが実行できるので最小値が取得できる
ただし、コード量は減らせるが計算量が多くなってしまうみたい

index.php
<?php
$book1 = new Book("やさしいJava", 2000);
$book2 = new Book("やさしいPHP", 1000);
$book3 = new Book("やさしいRuby", 3000);

$bookList = array( $book1,  $book2,  $book3);

usort($bookList, function($a, $b) {
    return $a->getPrice() > $b->getPrice();
});

var_dump($bookList[0]);

array_reduceを使う方法をコメントで教えてもらいました

index.php
<?php
$result = array_reduce($bookList, function ($c, $i) {
    return $c && $c->getPrice() <= $i->getPrice() ? $c : $i;
});

var_dump($result);
3
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3