Tbpgr Blog

Ruby プログラマ tbpgr(てぃーびー) のブログ

PHP | uasort

概要

uasort

詳細

uasortでユーザー定義のソートを適用する

サンプル

<?php
class Hoge {
  private $id;
  function __construct($id) {
    $this->id = $id;
  }

  function getId() {
    return $this->id;
  }
}

function idComparator($a, $b) {
  if ($a->getId() == $b->getId()) {
    return 0;
  }
  return ($a->getId() < $b->getId()) ? -1 : 1;
}

function idReverseComparator($a, $b) {
  if ($a->getId() == $b->getId()) {
    return 0;
  }
  return ($a->getId() < $b->getId()) ? 1 : -1;
}

$hoge1 = new Hoge(1);
$hoge2 = new Hoge(2);
$hoge3 = new Hoge(3);
$hoges = array($hoge2, $hoge1, $hoge3);
print_r($hoges);
print("\n");
uasort($hoges, 'idComparator');
print_r($hoges);
print("\n");
uasort($hoges, 'idReverseComparator');
print_r($hoges);
print("\n");

出力

Array
(
    [0] => Hoge Object
        (
            [id] => 2
        )

    [1] => Hoge Object
        (
            [id] => 1
        )

    [2] => Hoge Object
        (
            [id] => 3
        )

)

Array
(
    [1] => Hoge Object
        (
            [id] => 1
        )

    [0] => Hoge Object
        (
            [id] => 2
        )

    [2] => Hoge Object
        (
            [id] => 3
        )

)

Array
(
    [2] => Hoge Object
        (
            [id] => 3
        )

    [0] => Hoge Object
        (
            [id] => 2
        )

    [1] => Hoge Object
        (
            [id] => 1
        )

)

Rubyと比較

# encoding: utf-8
require 'pp'

class Hoge
  attr_reader :id
  def initialize(id)
   @id = id
  end
end

hoge1 = Hoge.new(1);
hoge2 = Hoge.new(2);
hoge3 = Hoge.new(3);
hoges = [hoge2, hoge1, hoge3]
pp hoges
pp hoges.sort {|one, other|one.id <=> other.id}
pp hoges.sort {|one, other|one.id <=> other.id}.reverse