我试图通过一些 XML 循环并执行一个动作,如果一个属性值匹配或不匹配它在循环的前一次迭代中的值。
传入的数据已经按类排序。
这是一些示例 XML 和代码
<character_list>
<character id="00001">
<name first="Name1"/>
<type class="Class A" classid="1"/>
</character>
<character id="00002">
<name first="Name2"/>
<type class="Class A" classid="1"/>
</character>
<character id="00003">
<name first="Name3"/>
<type class="Class B" classid="2"/>
</character>
<character id="00004">
<name first="Name4"/>
<type class="Class B" classid="2"/>
</character>
<character id="00005">
<name first="Name5"/>
<type class="Class B" classid="2"/>
</character>
<character id="00006">
<name first="Name6"/>
<type class="Class C" classid="3"/>
</character>
<character id="00007">
<name first="Name7"/>
<type class="Class D" classid="4"/>
</character>
<character id="00008">
<name first="Name8"/>
<type class="Class D" classid="4"/>
</character>
</character_list>
这是我的代码
<?php
$query = "data.xml";
$xml = file_get_contents($query);
try {
$dataobj = NEW SimpleXMLElement($xml);
}
catch(Exception $e) {
echo "Parsing error! ".$e->getMessage()." in ".basename($e->getFile()).":".$e->getLine()."!";
exit;
}
$lastclass = 0;
foreach ($dataobj as $xmldata) {
$currentclass = $xmldata->type['classid'];
if ($lastclass == $currentclass) {
echo $xmldata->name['first']." ";
}
else
{
echo "<br>";
echo $xmldata->type['class']." - ";
echo $xmldata->name['first']." ";
}
$lastclass = $xmldata->type['classid'];
}
?>
代码输出
Class A - Name1
Class A - Name2
Class B - Name3
Class B - Name4
Class B - Name5
Class C - Name6
Class D - Name7
Class D - Name8
预期产出
Class A - Name1 Name2
Class B - Name3 Name4 Name5
Class C - Name6
Class D - Name7 Name8
谁能看到我做错了什么以及如何纠正它?