It is necessary to add an array to another array with a given key value

Ok, I have an array like this, but it's not guaranteed to spill out in that order all the time ...

$array = array(
    'sadness' => array(
        'info' => 'some info',
        'info2' => 'more info',
        'value' => 'value',
    ),
    'happiness' => array(
        'info' => 'some info',
        'info2' => 'more info',
        'value' => 'the value',
    ),
    'peace' => array(
        'info' => 'some info',
        'info2' => 'more info',
        'value' => 'the value',
    )
);

      

Ok, and I would like to add this array right after the happiness key is defined. I cannot use the key to "peace", because it must come immediately after happiness, and peace may not come after happiness, because this array will change.

So here's what I need to add after happiness ...

$another_array['love'] = array(
    'info' => 'some info',
    'info2' => 'more info',
    'value' => 'the value of love'
);

      

So, the end result, after being injected immediately after happiness, should look like this:

$array = array(
    'sadness' => array(
        'info' => 'some info',
        'info2' => 'more info',
        'value' => 'value',
    ),
    'happiness' => array(
        'info' => 'some info',
        'info2' => 'more info',
        'value' => 'the value',
    ),
    'love' => array(
        'info' => 'some info',
        'info2' => 'more info',
        'value' => 'the value of love',
    ),
    'peace' => array(
        'info' => 'some info',
        'info2' => 'more info',
        'value' => 'the value',
    )
);

      

Can someone please give me a hand with this. Using array_shift, array_pop or array_merge doesn't help me at all as they go at the beginning and end of the array. I need to put it directly after the KEY position in $ array.

Thanks:)

+2


a source to share


2 answers


You are trying to create an array with two identical keys 'love'

. It's impossible.

EDIT:

You can do:



$new_array = array();
foreach($array as $k => $v) {
        $new_array[$k] = $v;
        if($k == 'happiness') {
                $new_array['love'] = $another_array['love'];
        }
}

      

working example

+2


a source


It seemed to me that you did not understand that in PHP all arrays are hashes (associative arrays). Therefore, the order cannot be influenced. If you want a specific order you need to use sorting etc. to define a specific order or use a simple array

$order = array ('love', 'happiness', 'pease');

      



Use the $ order array to access the $ array. In the $ order array, the keys are: 1, 2, 3 ...

0


a source







All Articles