[英]How to select and sort XML on repeating child node in PHP
我有一個有關繪畫數據的XML文件。 每幅畫都可以屬於一個或多個畫廊。 我需要能夠按畫廊選擇繪畫,然后將該列表按位置順序排序。 因此,例如,我具有以下XML:
<Paintings>
<Painting>
<Title>Painting 1</Title>
<Description>ABC</Description>
<Galleries>
<Gallery id="01">1</Gallery>
<Gallery id="02">3</Gallery>
</Galleries>
<Picturefile>painting1</Picturefile>
</Painting>
<Painting>
<Title>Painting 2</Title>
<Description>DEF</Description>
<Galleries>
<Gallery id="02">2</Gallery>
<Gallery id="03">2</Gallery>
</Galleries>
<Picturefile>painting2</Picturefile>
</Painting>
<Painting>
<Title>Painting 3</Title>
<Description>GHI</Description>
<Galleries>
<Gallery id="01">2</Gallery>
<Gallery id="03">1</Gallery>
</Galleries>
<Picturefile>painting3</Picturefile>
</Painting>
<Painting>
<Title>Painting 4</Title>
<Description>JKL</Description>
<Galleries>
<Gallery id="02">1</Gallery>
<Gallery id="03">3</Gallery>
</Galleries>
<Picturefile>painting4</Picturefile>
</Painting>
</Paintings>
例如,我需要選擇畫廊“ 02”中的繪畫,然后將它們按位置順序排序。 在上面的xml中,節點值代表該圖庫的排序順序。 對於選擇,我將使用:
$gallerypics = ($paintings->xpath("Painting/Galleries/Gallery[@id='$galleryid']"));
在這一點上我被卡住了。 然后,如何在該特定圖庫的節點值上排序$ gallerypics? 我可以選擇將排序順序設置為屬性而不是值,但是我仍然對如何對它排序感到困惑。 如果每幅畫只有一個Gallery節點,那是不費吹灰之力。 我對如何使用多個Gallery節點執行此操作感到困惑。 任何輸入,不勝感激。
基本想法只是選擇您想要的繪畫,將它們轉儲到一個數組中,然后根據您的標准對其進行排序 。
//$xml = your xml string
$galleryid = '02';
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$paintings = iterator_to_array($xpath->query("/Paintings/Painting[Galleries/Gallery/@id='$galleryid']"));
usort(
$paintings,
function ($a, $b) use ($xpath, $galleryid) {
$query = "number(Galleries/Gallery[@id='$galleryid'])";
return $xpath->evaluate($query, $a) - $xpath->evaluate($query, $b);
}
);
foreach ($paintings as $painting) {
echo $xpath->evaluate('string(Title)', $painting), "\n";
}
Painting 4
Painting 2
Painting 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.