views:

42

answers:

3

How can I add arrays into an existing array item?

For instance:

$user[$user->id] = array(//values);

But if that user needs another array added, I want all data to fall under that user ID in the array.

I want to store orders a user has made, so I can look up all orders on the fly by user ID in the $user array above.

A: 

Have you tried something like:

$user[$id] = array_merge($user[$id], array(//values));
Lone Ranger
This did not work.
Kevin
How exactly did it not work? Any errors?
codaddict
It all came out [empty string]
Kevin
A: 
$user[$user->id]['orders'] = array();

Or

$user[$user->id] = array(
    'orders' => array(
        array(// data for order #1),
        array(// data for order #2),
        array(// data for order #3)
    );
);

// Looping over the orders
foreach($user[$user->id]['orders'] as $order) {
    // Do something with the order
}
mellowsoon
A: 

Give the orders a key

$user[$user->id] = array( "orders" => array(values) );

dhisnotnull
I am looping over orders, and each user may have multiple orders. Wouldn't the key be overwritten?
Kevin
@Kevin - I updated my answer to show multiple orders, but it should be clear by now how arrays within arrays works.
mellowsoon
@kevin - agree with mellowsoon
dhisnotnull