phparraysloopsnested-loopsamazon-mws

Complex MultiDimensional Array


I am using an API to get the data and it returns data in the array of arrays. Now I want to get the data I need and move into a new array.

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

I want to fetch the amount from the innermost array. But I am not able to iterate through all the nested array and can't find the solution. I can get the value what I want through this code. but its getting 1, I need dynamic data.

    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;
}

Also I tried to loop through all arrays but its looking so messy.

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']);
                }
            }
       }
    }
}

Please tell me what is the right way to iterate through the items and get the Amounts I needed. Thanks


Solution

  • If the structure of the data is consistent you can use something like this:

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