Php object sorting properties

I want to sort the properties of an object so that I can scroll them in a specific order.

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

Now I want to skip these properties as follows:

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

now the loop order should be "title", then "author", "date" and "id"

How to do it? (I cannot change the order of the properties in the class of the object, because there are any properties defined there, I get the object from the database using "MyActiveRecord")

+4
source share
3 answers

Not sure if this is the answer to your question, but you can try:

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

Alternatively, you can extract the properties of the book (instead of hard coding them) and sort them in your custom order:

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

You can wrap your source object in something that implements the Iterator interface and returns the properties of the source object in the specified 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 
+4
source

Try it. The difference between this method and the method proposed in the first answer is that the get_class_vars method returns the default properties of the class, while get_object_vars returns the properties of the object specified .

 <?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>"; ?> 
+2
source

Source: https://habr.com/ru/post/1311403/


All Articles