本文介绍了按子节点PHP SimpleXML排序xml div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在xml文件中有一个<div>的列表.我正在使用php的simpleXML解析文件

so I have a list of <div>'s in an xml file. I'm parsing the file using php's simpleXML

我可以使用以下命令生成所有div的数组:

I can generate an array of all the divs with the following:

$divArray = $xmldoc->text->body->children();

但是现在我想通过div中的不同childNode(作者,标题,日期)对$ divArray进行排序.

But now I would like to order the $divArray by different childNodes (author, title, date) within the div.

div看起来像这样.

The div looks like this.

<div>
    <bibl>
       <author>
       <title>
       <date>
   </bibl>
</div>

那我怎么拿$ divArray并按<author><title><date>对其排序?

So how can I take $divArray and sort it by <author> or <title> or <date>?

感谢您的帮助.jw

Thanks for your help.jw

推荐答案

基本过程是

  1. SimpleXMLElement投射到数组中
  2. 编写一个接受两个SimpleXMLElement自变量的比较函数
  3. 使用usort()
  4. 用比较功能对数组进行排序
  1. cast a SimpleXMLElement into an array
  2. write a comparison function that accepts two SimpleXMLElement arguments
  3. sort the array with the comparison function using usort()

我只能猜测您的原始XML结构,但我认为它看起来像这样:

I can only guess at your original XML structure, but I think it looks something like this:

$xml = <<<EOT
<root>
<text>
    <body>
        <div>
            <bibl>
                <author>A</author>
                <title>A</title>
                <date>1</date>
            </bibl>
        </div>
        <div>
            <bibl>
                <author>B</author>
                <title>B</title>
                <date>2</date>
            </bibl>
        </div>
        <div>
            <bibl>
                <author>D</author>
                <title>D</title>
                <date>4</date>
            </bibl>
        </div>
        <div>
            <bibl>
                <author>C</author>
                <title>C</title>
                <date>3</date>
            </bibl>
        </div>
    </body>
</text>
</root>
EOT;

$xmldoc = new SimpleXMLElement($xml);

第1步:转换为数组.请注意,您的 $divArray 实际上不是数组

Step 1: Cast to array. Note that your $divArray is not actually an array!

$divSXE = $xmldoc->text->body->children(); // is a SimpleXMLElement, not an array!
// print_r($divSXE);
$divArray = array();
foreach($divSXE->div as $d) {
    $divArray[] = $d;
}
// print_r($divArray);

第2步:编写比较功能.由于数组是SimpleXMLElement的列表,因此比较函数必须接受SimpleXMLElement自变量. SimpleXMLElement需要显式转换才能获取字符串或整数值.

Step 2: write a comparison function. Since the array is a list of SimpleXMLElements, the comparison function must accept SimpleXMLElement arguments. SimpleXMLElements need explicit casting to get string or integer values.

function author_cmp($a, $b) {
    $va = (string) $a->bibl->author;
    $vb = (string) $b->bibl->author;
    if ($va===$vb) {
        return 0;
    }
    return ($va<$vb) ? -1 : 1;
}

第3步:使用usort()

usort($divArray, 'author_cmp');
print_r($divArray);

这篇关于按子节点PHP SimpleXML排序xml div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 00:57