我有多个XML文档,其中包含来自API的输出 - 此输出是来自我们的票务系统的支持票据。我正在尝试计算状态设置为特定状态的票证。
XML输出如下所示(尽管7个文档中有更多请求元素)。
<response uri="/api/xml/getRequestsByView">
<result>
<status>Success</status>
<statuscode>200</statuscode>
<requests>
<request>
<form name="requestID">12345</form>
<form name="userTimeFormat">dd MMM yyyy, HH:mm:ss</form>
<form name="contact">Name</form>
<form name="status">Open</form>
<form name="statusID">1</form>
<form name="priority">P3 Minor</form>
<form name="supportRep"/>
<form name="supportRepCostPerHour">0.00</form>
<form name="createdTime">20 Jun 2017, 08:22:00</form>
<form name="updatedTime">20 Jun 2017, 08:23:11</form>
<form name="dueByTime"/>
<form name="isOverDue">false</form>
<form name="accountID"/>
<form name="account"/>
<form name="subject">Subject Name</form>
</request>
<request>
<form name="requestID">12346</form>
<form name="userTimeFormat">dd MMM yyyy, HH:mm:ss</form>
<form name="contact">Contact Name</form>
<form name="status">Open</form>
<form name="statusID">1</form>
<form name="priority">P3 Minor</form>
<form name="supportRep"/>
<form name="supportRepCostPerHour">0.00</form>
<form name="createdTime">20 Jun 2017, 08:21:58</form>
<form name="updatedTime">20 Jun 2017, 08:23:10</form>
<form name="dueByTime"/>
<form name="isOverDue">false</form>
<form name="accountID"/>
<form name="account"/>
<form name="subject">Subject Name</form>
</request>
</requests>
</result>
到目前为止,我创建了以下函数 - 我从下面得到的输出是“1440”。它应该工作,因为当我替换count元素以回显每个匹配时,输出显示具有匹配状态的每个票证的状态 - 只是计数元素似乎不按预期运行。
function countPriority($status){
$files = array("includes/xml-1.xml","includes/xml-2.xml","includes/xml-3.xml","includes/xml-4.xml","includes/xml-5.xml","includes/xml-6.xml","includes/xml-7.xml");
$count = 0;
foreach ($files as $url) {
$xml = simplexml_load_file($url);
foreach ($xml->result->requests->request as $request){
if ($request->form['3'] == $status){
$count+= count($request);
}
}
return $count;
}
}
对于PHP / Coding,我是一个完整的新手,因此非常感谢任何建议或帮助。
答案 0 :(得分:1)
这里似乎有一个错误:$count+= count($request);
。如果您只是想计算具有特定状态的票数,那么您只需将计数器加1,例如$count++;
。相反,您正在做的是将$count
的值增加每个$request
中的元素数量。
另外,正如评论中所指出的,您应该将return
语句移出foreach
循环,否则您的方法只会循环遍历数组中的第一个文件。
所以你的方法应该是这样的:
function countPriority($status){
$files = array("includes/xml-1.xml","includes/xml-2.xml","includes/xml-3.xml","includes/xml-4.xml","includes/xml-5.xml","includes/xml-6.xml","includes/xml-7.xml");
$count = 0;
foreach ($files as $url) {
$xml = simplexml_load_file($url);
foreach ($xml->result->requests->request as $request){
if ($request->form['3'] == $status){
$count++;
}
}
}
return $count;
}