复杂多维数组

问题描述 投票:0回答:2

我正在使用 API 来获取数据,它返回数组数组中的数据。现在我想获取我需要的数据并移入一个新数组。

  $shipments = Array
    (
      [0] => Array
        (
          [AmazonOrderId] => 12321313
          [SellerOrderId] => 
          [MarketplaceName] => Amazon.com
          [PostedDate] => 2018-10-01T14:21:46Z
          [ShipmentItemList] => Array
            (
              [0] => Array
                (
                  [SellerSKU] => 12-12321-1231
                  [OrderItemId] => 1212313
                  [QuantityShipped] => 1
                  [ItemChargeList] => Array
                    (
                      [0] => Array
                        (
                          [ChargeType] => Principal
                          [Amount] => 6.95
                          [CurrencyCode] => USD
                        )
                      [1] => Array
                        (
                          [ChargeType] => Principal
                          [Amount] => 6.95
                          [CurrencyCode] => USD
                         )
                     )
               )
          )
     )
 )

我想从最里面的数组中获取金额。但我无法迭代所有嵌套数组,也找不到解决方案。 我可以通过这段代码得到我想要的值。但它得到1,我需要动态数据。

    function myfunction($products, $field, $value)
{
   foreach($products as $key => $product)
   {
      if ( $product[$field] === $value )
         return $key;
         var_dump($product[$field][0]['ItemChargeList'][0]['Amount']);
   }
   return false;
}

我也尝试循环遍历所有数组,但它看起来很混乱。

if($shipment){
    foreach($shipment as $shiptmentList){
        foreach($shiptmentList as $key => $shiporder){
            foreach($shiporder as $key => $itemcharge){
                foreach($itemcharge as $key=> $eachcharge){
                    var_dump($eachcharge[0]['Amount']);
                }
            }
       }
    }
}

请告诉我迭代项目并获取我需要的金额的正确方法是什么。谢谢

php arrays loops nested-loops amazon-mws
2个回答
1
投票

如果数据的结构是一致的,你可以使用这样的东西:

 foreach($shipments as $shipment)
    foreach($shipment["ShipmentItemList"] as $itemList)
        foreach($itemList["ItemChargeList"] as $chargedItem) {
                echo $chargedItem["Amount"];
                echo print_r($chargedItem);
        }

0
投票

从 PHP 5.1 开始,一个简单的方法是使用 RecursiveArrayIterator 类,尝试一下它的工作原理:

$flattened = new RecursiveArrayIterator($shipments); $flattened = new RecursiveIteratorIterator($flattened);

foreach($flattened as $key => $v) { 
  //echo $v, " "; 
  if($key === 'Amount') $som += $v;

} var_dump($som);

© www.soinside.com 2019 - 2024. All rights reserved.