php对象的排序属性 [英] php sort properties of object

查看:88
本文介绍了php对象的排序属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如:我有一个具有以下属性的对象"book":"id","title","author","date".

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

现在循环的顺序必须是标题",然后是作者",日期"和"id"

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

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

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

推荐答案

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

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

这篇关于php对象的排序属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆