php排序对象的属性

时间:2010-05-31 10:30:48

标签: php sorting object

我想对对象的属性进行排序,以便我可以按照定义的顺序遍历它们。

例如:我有一个带有以下属性的对象'book':'id','title','author','date'。

现在我想循环遍历这些属性:

foreach($book as $prop=>$val)
//do something

现在循环的顺序必须是'title',然后是'author','date'和'id'

怎么会这样做? (我无法更改对象类中属性的顺序,因为那里没有定义任何属性,我使用'MyActiveRecord'从数据库中获取对象)

3 个答案:

答案 0 :(得分:8)

不确定这是否能解答您的问题,但您可以尝试:

$properties = array('title', 'author', 'date', 'id');
foreach ($properties as $prop) {
    echo $book->$prop;
}

或者,您可以提取图书的属性(而不是硬编码),并使用自定义顺序对其进行排序:

$props = get_class_vars(get_class($book));
uasort($props, 'my_properties_sorting_function');

答案 1 :(得分:4)

您可以将源对象包装为实现Iterator interface的内容,并以给定的排序顺序返回源对象的属性。

class Foo implements Iterator {
  protected $src;
  protected $order;
  protected $valid;

  public function __construct(/*object*/ $source, array $sortorder) {
    $this->src = $source;
    $this->order = $sortorder;
    $this->valid = !empty($this->order);
  }
  public function current() { return $this->src->{current($this->order)}; }
  public function key() { return key($this->order); }
  public function next() { $this->valid = false!==next($this->order); }
  public function rewind() { reset($this->order); $this->valid = !empty($this->order); }

  public function valid() { return $this->valid; }
}

class Book {
  public $id='idval';
  public $author='authorval';
  public $date='dateval';
  public $title='titleval';
}


function doSomething($it) {
  foreach($it as $p) {  
    echo '  ', $p, "\n";
  }
}

$book = new Book;
echo "passing \$book to doSomething: \n";
doSomething($book);

$it = new Foo($book, array('title', 'author', 'date', 'id'));
echo "passing \$it to doSomething: \n";
doSomething($it);

打印

passing $book to doSomething: 
  idval
  authorval
  dateval
  titleval
passing $it to doSomething: 
  titleval
  authorval
  dateval
  idval

答案 2 :(得分:3)

试试这个。此方法与第一个响应中提出的方法之间的区别在于方法 get_class_vars 返回类的默认属性,而 get_object_vars 返回给定对象的属性。

<?php

class Book {
  public $title;
  public $author;
  public $date;
  public $id;
}

  $b = new Book();
  $b->title = "title";

  $object_vars = get_object_vars($b);
  ksort($object_vars);

  foreach($object_vars as $prop=>$val)
        echo $prop."->".$val."<br>";

?>