将 usor 与 simplexml 一起使用 [英] Using usort with simplexml
本文介绍了将 usor 与 simplexml 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了一个问题,我的值没有以正确的顺序结束.
I'm having a problem where none of my values are ending up in the right order.
$xml = file_get_contents('admin/people.xml');
$x = new SimpleXMLElement($xml);
$sort=$x->person;
function cmp($a, $b){
if ($a->age == $b->age) {
return 0;
}
return ($a->age < $b->age) ? -1 : 1;
}
usort($sort, 'cmp');
foreach ($sort as $key => $value) {
echo "$key: $value->age<br>";
}
从我读过的所有内容来看,这应该有效,但没有.这是 XML:
From everything I've read, this should work, but it doesn't. Here is the XML:
<people>
<person>
<name>Frank</name>
<age>12</age>
</person>
<person>
<name>Jim</name>
<age>6023</age>
</person>
<person>
<name>Tony</name>
<age>234</age>
</person>
<person>
<name>Bob</name>
<age>2551</age>
</person>
<person>
<name>Dave</name>
<age>21</age>
</person>
<person>
<name>Trevor</name>
<age>56</age>
</person>
<person>
<name>Mike</name>
<age>89</age>
</person>
</people>
我得到的结果是这样的,这根本不是一种秩序!
And the result I'm getting is this, which is no kind of order at all!
0: 6023
2: 21
3: 234
4: 12
6: 56
7: 2551
8: 89
有什么想法吗?
非常感谢...
推荐答案
usort
接受数组.- 当您比较两个 SimpleXMLElements 时,应该对它们进行转换.
所以更改代码
$sort=$x->person;
function cmp($a, $b){
if ($a->age == $b->age) {
return 0;
}
return ($a->age < $b->age) ? -1 : 1;
}
到
$sort = array();
foreach ($x->person as $person) {
$sort[] = $person;
}
function cmp($a, $b){
if ((int)$a->age == (int)$b->age) {
return 0;
}
return ((int)$a->age < (int)$b->age) ? -1 : 1;
}
会给你正确的结果.
这篇关于将 usor 与 simplexml 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文