编辑:分组,先排序,然后输出。
致谢: [GZipp][1] 在这篇文章sort_obj_arr
中编写的函数。
// define it
$xml = simplexml_load_string($x); // assuming XML in $x
$grades = $xml->xpath("//Entry");
// sort it
sort_obj_arr($grades,'Field_3',SORT_ASC);
// print it
$g = "";
foreach ($grades as $grade) {
if ($grade->Field_3 <> $g) {
$g = (string)$grade->Field_3;
echo "<br />*** grade $g ***<br />";
}
echo $grade->Field_1 . " " . $grade->Field_2 . "<br />";
}
// function for sorting
function sort_obj_arr(& $arr, $sort_field, $sort_direction) {
$sort_func = function($obj_1, $obj_2) use ($sort_field, $sort_direction) {
if ($sort_direction == SORT_ASC) {
return strnatcasecmp($obj_1->$sort_field, $obj_2->$sort_field);
} else {
return strnatcasecmp($obj_2->$sort_field, $obj_1->$sort_field);
}
};
usort($arr, $sort_func);
}
看到它工作:http ://codepad.viper-7.com/Saka16
首先:您的 XML 无效,您需要<>
并且节点名称中没有空格:
<Entries>
<Entry>
<Entry_Id>1</Entry_Id>
<Field_1>John</Field_1>
<Field_2>Doe</Field_2>
<Field_3>8</Field_3>
</Entry>
</Entries>
要选择具有特定值的节点,请使用xpath
:
$xml = simplexml_load_string($x); // assuming XML in $x
$grades = $xml->xpath("//Entry[Field_3 = '8']");
echo "** grade: " . $grades[0]->Field_3 . "**<br />";
foreach ($grades as $grade) {
echo $grade->Field_1 . " " . $grade->Field_2 . "<br />";
}
看到它工作:http ://codepad.viper-7.com/Lke7gc