使用php将XML文件按升序排序 [英] Sorting XML File into ascending order using php
本文介绍了使用php将XML文件按升序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 xml 文件,其中包含大约 60 本书,我需要使用 php 从已借用的计数中按升序排列到目前为止我的代码显示所有书籍但不会排序?任何帮助都会非常感谢
i have an xml file which contains around 60 books which i need to put into ascending order from the borrowedcount using php so far my code shows all the books but will not sort? any help would be really appriecated
PHP
<?php
$xmlassignDoc = new DOMDocument();
$xmlassignDoc->load("books.xml");
$books = $xmlBookDoc->getElementsByTagName("item");
foreach($books as $list)
{
$course = $list->getElementsByTagName("course");
$course = $course->item(0)->nodeValue;
//HERE is where the GET function will be
if ($course == "CC150")
{
print_r($array);
$id = $list->getAttribute("id");
echo "<b>Book ID: </b> $id <br>";
$title = $list->getElementsByTagName("title");
$title = $title->item(0)->nodeValue;
echo "<b>Title: </b> $title <br>";
$isbn = $list->getElementsByTagName("isbn");
$isbn = $isbn->item(0)->nodeValue;
echo "<b>ISBN: </b> $isbn <br>";
$borrowed = $list->getElementsByTagName("borrowedcount");
$borrowed = $borrowed->item(0)->nodeValue;
echo "<b>Borrowed Count: </b> $borrowed <br>";
echo "<br>";
}
}
//print $xmlBookDoc->saveXML();
?>
xml 文件
<?xml version="1.0" encoding="utf-8"?>
<bookcollection>
<items>
<item id="51390">
<title>Management of systems development /</title>
<isbn>0091653215</isbn>
<url>http://library.hud.ac.uk/catlink/bib/51390</url>
<borrowedcount>45</borrowedcount>
<courses>
<course>CC140</course>
<course>CC210</course>
</courses>
</item>
<item id="483">
<title>Database systems management and design /</title>
<isbn>0877091153</isbn>
<url>http://library.hud.ac.uk/catlink/bib/483</url>
<borrowedcount>28</borrowedcount>
<courses>
<course>CC140</course>
</courses>
</item>
<item id="585842">
<title>E-learning skills /</title>
<isbn>0230573126</isbn>
<url>http://library.hud.ac.uk/catlink/bib/585842</url>
<borrowedcount>5</borrowedcount>
<courses>
<course>CC157</course>
</courses>
</item>
推荐答案
我的解决方案:
$books = array();
$xml = simplexml_load_file('books.xml');
foreach($xml->items->item as $item) {
$books[] = array(
'id' => (string)$item->attributes()->id,
'title' => (string)$item->title,
'isbn' => (string)$item->isbn,
'course' => (string)$item->courses->course[0],
'borrowed_count' => intval($item->borrowedcount)
);
}
array_sort_by_column($books, 'borrowed_count');
var_dump($books);
还有排序功能:
function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
$reference_array = array();
foreach($array as $key => $row) {
$reference_array[$key] = $row[$column];
}
array_multisort($reference_array, $direction, $array);
}
这篇关于使用php将XML文件按升序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文