如何使用键/索引每 4 个元素提取数组

How to extract Array using Key / Index every 4 elements

我有一个数组,如下所示: http://pastebin.com/jtFBeQ88

(一小部分,使用link查看完整数组)

string(635) "<InventoryStatus>
<ItemID>171770899535</ItemID>
<Quantity>0</Quantity>
<SKU>0000003830-000011299</SKU>
</InventoryStatus>
<InventoryStatus>
<ItemID>171770899535</ItemID>
<Quantity>0</Quantity>
<SKU>0000003830-000011303</SKU>
</InventoryStatus>
<InventoryStatus>
<ItemID>171770899535</ItemID>
<Quantity>0</Quantity>
<SKU>0000003830-000011583</SKU>
</InventoryStatus>
<InventoryStatus>
<ItemID>171770899535</ItemID>
<Quantity>0</Quantity>
<SKU>0000003830-000013149</SKU>
</InventoryStatus>
<InventoryStatus>
<ItemID>171770899535</ItemID>
<Quantity>0</Quantity>
<SKU>0000003830-000013154</SKU>
</InventoryStatus>

我正在尝试从 InventoryStatus 级别提取 4 个元素集中的数据。 此输出的示例如下所示。

 <InventoryStatus>
<ItemID>171770899535</ItemID>
<Quantity>0</Quantity>
<SKU>0000003830-000011303</SKU>
</InventoryStatus>
<InventoryStatus>
<ItemID>171770899535</ItemID>
<Quantity>0</Quantity>
<SKU>0000003830-000011583</SKU>
</InventoryStatus>
<InventoryStatus>
<ItemID>171770899535</ItemID>
<Quantity>0</Quantity>
<SKU>0000003830-000013149</SKU>
</InventoryStatus>
<InventoryStatus>
<ItemID>171770899535</ItemID>
<Quantity>0</Quantity>
<SKU>0000003830-000013154</SKU>
</InventoryStatus>

我一直在使用array_slice,但我似乎只能指定一个计数。 所以如果我使用 4,那么它的 4 个节点从顶部向下。 我可以使用 20 的计数,因为每个节点始终为 5。但这是假设没有添加其他节点。

如何使用密钥而不是数字来提取数据。

foreach (array_slice($xmlReq, 4) as $slice) {
    echo implode(' ', $slice), "\n";      }

大致如下:

foreach (array_slice(xmlReq->InventoryStatus, 4) as $slice {
Echo $slice ."Should show JUST 4 Node sets of InventoryStatus"
}

也许array_slice不是解决这个问题的方法,如果不是的话用什么更合适

使用array_chunk()

foreach (array_chunk($xmlReq, 4) as $slice) {
    echo implode(' ', $slice), "\n";
}

来自手册http://php.net/manual/en/function.array-chunk.php

array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
Chunks an array into arrays with size elements. The last chunk may contain less than size elements.

将其视为 XML 并解析它,例如SimpleXml:

$xml = simplexml_load_string("<set>$string</set>"); // assume XML in $string
$count = 0;
foreach ($xml->xpath("/set/InventoryStatus") as $item) {
    echo $item->asXML() . PHP_EOL;
    $count++;
    if ($count > 3) break;
}  

$string包裹在根标签中,使其成为一个对象,遍历<InventoryStatus>个节点,echo个节点,数到4。 对整个 array 个字符串执行此操作。

查看实际效果:https://eval.in/537665