jim jim - 4 months ago 41
PHP Question

php array remove key and shift values up

I've researched topics similar to this but not exactly what I'm looking to do.
I have a multidimensional array like the following.

[code] => BILL
[assets] => Array
(
[en] => Array
(
[datatype] => My Assets
[data] => Array
(
[Corporate Equity] => 41
[Global Equity] => 24
[Fixed Income – Government] => 22
[Fixed Income – Corporate] => 8.1
[Other] => 3.57
)

)

)


I'd like to remove the first inner array, but preserve the values. Shift them up one level in the array so that it looks like this.

[code] => BILL
[assets] => Array
(

[datatype] => My Assets
[data] => Array
(
[Corporate Equity] => 41
[Global Equity] => 24
[Fixed Income – Government] => 22
[Fixed Income – Corporate] => 8.1
[Other] => 3.57
)


)


This is just the beginning of the array, there are other instances of the same key
[en]
at the same level.

I've tried unset, array_shift and others but I need to keep the contents of
[en]
, just shift them up one level in the array.

Answer

You can use array_map which returns an array which contains all elements of the previous array after applying the function.

In this case it will simply take the array at index en and add it's contents to the new array.

http://php.net/manual/en/function.array-map.php

$arr = array('assets' => array(
    'en' => array(
        'datatype' => 'My Assets',
        'data' => array(
            'Corporate Equity' => 41,
            'Global Equity' => 24,
             'Fixed Income – Government' => 22,
             'Fixed Income – Corporate' => 8.1,
             'Other' => 3.57
        )
    )
));

$new_arr = array_map(function ($e) {
    return $e['en'];
}, $arr);