PHP - 从元素组中检索最低和最高值
问题描述:
无法找到正确的方法来执行以下操作:我有xml,其中包含元素,其中每个元素具有属性顺序,值范围为0-3。它们按该属性排序(0,1,2,3,0,1,2,3 ...)并且是兄弟姐妹。一些元素可能会有所不同,并且文档中的第一个元素不以0开头,因为XML每4小时刷新一次,并且每刷新一次,当前的第一个元素get被删除,并且行中的下一个元素占据第一个位置。例如:在凌晨0:00,第一个元素的属性order =“0”。在6:00它被移除,下一个兄弟姐妹需要他(第一个)属性order =“1”的地方。PHP - 从元素组中检索最低和最高值
我想为0-3的一组元素(第一组元素可能有0,1,2或3的顺序)进行循环,并检索最低和最高每个组子节点的值。例如:
Lopping the bottom structure should print:
11, 82
2, 92
1, 211
...
<parent>
<!-- Group 1 -->
<element order="2">
<node value="30" />
<node value="82" /> <!-- This is the highest of the Group 1 -->
<node value="25" />
</element>
<element order="3">
<node value="12" />
<node value="52" />
<node value="11" /> <!-- This is the lowest of the Group 1 -->
</element>
<!-- Group 2 -->
<element order="0">
<node value="21" />
<node value="78" />
<node value="33" />
</element>
<element order="1">
<node value="35" />
<node value="57" />
<node value="88" />
</element>
<element order="2">
<node value="22" />
<node value="92" /> <!-- This is the highest of the Group 2 -->
<node value="81" />
<node value="19" />
</element>
<element order="3">
<node value="2" /> <!-- This is the lowest of the Group 2 -->
<node value="30" />
<node value="44" />
</element>
<!-- Group 3 -->
<element order="0">
<node value="12" />
<node value="99" />
<node value="43" />
</element>
<element order="1">
<node value="65" />
<node value="211" /> <!-- This is the highest of the Group 3 -->
<node value="16" />
</element>
<element order="2">
<node value="32" />
<node value="55" />
<node value="77" />
<node value="1" /> <!-- This is the lowest of the Group 3 -->
</element>
<element order="3">
<node value="68" />
<node value="74" />
<node value="21" />
</element>
<!-- Group 4 -->
...
</parent>
希望这个问题不被广泛提出。这些注释不包含在XML中。
答
这是一种方法。
此解决方案仅适用于属性是按例如1, 3, 4
而不是例如3, 0, 4
。
$string = <<<XML
<!-- XML data goes here -->
XML;
// suppress some errors
libxml_use_internal_errors(true);
$xml = simplexml_load_string($string);
// step 1: group all the values
// keep track of the previous order to determine when we have a new group
// INF is just an arbitrarily large number to start the first group
$prevOrder = INF;
$groups = [];
$i = -1;
foreach ($xml->element as $element) {
$order = (int) $element->attributes()['order'];
// start a new group if the current order is smaller than the previous order
if ($order <= $prevOrder) {
$groups[++$i] = [];
}
// store the next values in that group
foreach ($element->node as $node) {
$groups[$i][] = (int) $node->attributes()['value'];
}
$prevOrder = $order;
}
// step 2: get the minimum and maximum of each group
foreach ($groups as $group) {
printf('%d, %d<br>', min($group), max($group));
}
您到目前为止尝试过什么? –
什么都没有:/我用foreach试过,但坚持要从每个组中检索最小/最大值。我猜我应该为每个while循环创建一个数组,并将值放入相应的数组中。 – g5wx
随着XML get的更新(基于一天的时间)订单更改。例如:在凌晨0:00,它的order =“0”,但在早上6:00它被删除,所以下一个节点变成第一个(order =“1”)。 – g5wx