Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php sort properties of object

I want to sort the properties of an object so I can loop through them in a defined order.

for example: I have an object 'book' with the following properties: 'id', 'title', 'author', 'date'.

Now i want to loop through these properties like this:

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

now the order of the loop has to be 'title', then 'author', 'date' and 'id'

How would one do this? (I can't change the order of the properties in the class of the object because there arent any properties defined there, I get the object from the database with 'MyActiveRecord')

like image 575
user324107 Avatar asked May 31 '10 10:05

user324107


2 Answers

Not sure if this answers to your question, but you could try :

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

Alternatively, you could extract the properties of the book (instead of hardcoding them), and sort them with your custom order :

$props = get_class_vars(get_class($book));
uasort($props, 'my_properties_sorting_function');
like image 171
mexique1 Avatar answered Oct 14 '22 23:10

mexique1


You could wrap your source object into something that implements the Iterator interface and returns the properties of the source object in a given sort order.

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

prints

passing $book to doSomething: 
  idval
  authorval
  dateval
  titleval
passing $it to doSomething: 
  titleval
  authorval
  dateval
  idval
like image 23
VolkerK Avatar answered Oct 14 '22 21:10

VolkerK