dourang8305 2016-03-16 15:02
浏览 69
已采纳

如何使用Key / Index每4个元素提取数组

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

  • 写回答

2条回答 默认 最新

  • dongshai8330 2016-03-16 15:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题