I have an array that looks like: http://pastebin.com/jtFBeQ88
(Small section of it, use link to see full Array)
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>
I am trying to extract data in set of 4 elements from InventoryStatus level. An example of this output would look like this.
<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>
I have been using array_slice, but i only seem to be able to specify a count. So if i use 4, then its 4 Nodes down from Top. I could use a count of 20, As each node is always 5. But this is assuming no additional nodes ever get added.
How does one go about doing this, using the Key to extract the data instead of a number.
foreach (array_slice($xmlReq, 4) as $slice) {
echo implode(' ', $slice), "
"; }
Something along the lines of:
foreach (array_slice(xmlReq->InventoryStatus, 4) as $slice {
Echo $slice ."Should show JUST 4 Node sets of InventoryStatus"
}
Maybe array_slice is not the way to go about it, If not what would be more suitable to use
Use array_chunk()
foreach (array_chunk($xmlReq, 4) as $slice) {
echo implode(' ', $slice), "
";
}
From the manual 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.
Treat it as XML and parse it, e.g. with 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;
}
Wrap $string
in a root tag, make it an object, iterate over the <InventoryStatus>
nodes, echo
them, count to 4. Do this for your entire array
of strings.
see it in action: https://eval.in/537665