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条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。