【问题标题】:Using usort with simplexml将 usort 与 simplexml 一起使用
【发布时间】:2011-11-10 08:10:02
【问题描述】:

我遇到了一个问题,我的值都没有以正确的顺序结束。

        $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:

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

而我得到的结果就是这样,这根本不是一种命令!

0: 6023
2: 21
3: 234
4: 12
6: 56
7: 2551
8: 89

有什么想法吗?

非常感谢...

【问题讨论】:

标签: php xml xpath simplexml usort


【解决方案1】:
  • 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;
}

会给你正确的结果。

【讨论】:

    【解决方案2】:

    为了使用usort,您需要将您的 SimpleXMLElement 转换为数组。这是一种快速的方法 (http://www.php.net/manual/en/book.simplexml.php#105330):

    $xml = file_get_contents('admin/people.xml');
    $x = new SimpleXMLElement($xml);
    $json = json_encode($x);
    $xml_array = json_decode($json,TRUE);
    $sort = $xml_array['person'];
    

    现在您可以将$sort 传递给usort,它会正常工作。将$a-&gt;age 替换为$a['age']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多