Ayad Mfs
Ayad Mfs

Reputation: 33

Dynamically add data to a multidimensional array

For my ecommerce application that expects name-value pairs, I have the following approved code:

function create_example_purchase() {
    set_credentials();
    $purchase = array(
        'name'        => 'Digital Good Purchase Example',
        'description' => 'Example Digital Good Purchase',
        'amount'      => '12.00', // sum of all item_amount
        'items'       => array(
            array( // First item
                'item_name'        => 'First item name',
                'item_description' => 'a description of the 1st item',
                'item_amount'      => '6.00',
                'item_tax'         => '0.00',
                'item_quantity'    => 1,
                'item_number'      => 'XF100',
            ),
            array( // Second item
                'item_name'        => 'Second Item',
                'item_description' => 'a description of the 2nd item',
                'item_amount'      => '3.00',
                'item_tax'         => '0.00',
                'item_quantity'    => 2,
                'item_number'      => 'XJ100',
            ),
        )
    );

    return new Purchase( $purchase); 
}

I would like to get the $items array inside the associative $purchase array dynamically from the shipping cart.

Is there a way to generate exactly the same output above?

My dirty solution is to write the $purchase array as string inclusive the generated $items array in a file then include it later in the called script.

Upvotes: 0

Views: 2103

Answers (1)

ncremins
ncremins

Reputation: 9200

$itemsArray = function_that_returns_your_2d_item_array();

$purchase['items'] = $itemsArray;

or if the function_that_returns_your_2d_item_array() returns a 2d array indexed by 'items' you could do:

$purchase = array_merge($purchase, $itemsArray);

Upvotes: 0

Related Questions