funguy
funguy

Reputation: 2160

How to place a loop into an array php

A newbie question.

I have this data coming in:

foreach ( $items as $item_id => $item_data ) {
  $item_data['name'];
  $item_data['qty'];
  $item_data['variation_id'];
  ...
}

So, it can be more than one item.

How to place this data into this:

     $order = $pf->post('orders',
    [

        'items' => [
            [
                'variant_id' => $item_data['variation_id'],// Small poster
                'name' => $item_data['name'], // Display name
                'retail_price' => $order_details['_order_total'][0], // Retail price for packing slip
                'quantity' => $item_data['qty'],
                'files' => [
                    [
                        'url' => 'http://example.com/files/posters/poster_1.jpg',
                    ],
                ],
            ],
        ],
    ]
);

I mean the looping part. As you can see right now it is kind of hardcoded and for one item only. How it should look like if there is more items?

Upvotes: 0

Views: 36

Answers (1)

Oliver
Oliver

Reputation: 883

This should do the trick for you:

$mappedItems = [];
foreach ( $items as $item_id => $item_data ) {
  $mappedItems[] = [
     'variant_id' => $item_data['variation_id'],// Small poster
     'name' => $item_data['name'], // Display name
     'retail_price' => $order_details['_order_total'][0], // Retail price for packing slip
     'quantity' => $item_data['qty'],
     'files' => [
         [
           'url' => 'http://example.com/files/posters/poster_1.jpg',
         ],
      ],
  ];
}

$order = $pf->post('orders',
[
    'items' => $mappedItems
]

Upvotes: 1

Related Questions