3

I have a simple multidimensional array like the following

$array = array(
    array('key1'=>array('a','b')),
    array('key2'=>array('c','d'), 'key3'=>array('e','f')),
    array('key4'=>array('g','h'), 'key5'=>array('i','j'), 'key6'=>array('k','l', 'm'))
);

and I would reset its first level like the following

$array = array(
    'key1'=>array('a','b'),
    'key2'=>array('c','d'),
    'key3'=>array('e','f'),
    'key4'=>array('g','h'),
    'key5'=>array('i','j'),
    'key6'=>array('k','l','m')
);

I know it's quite easy with a foreach loop to achieve, but I'm wondering if it's possible to do it using one line code.

What I tried so far

array_map('key', $array);

but it returns only the first key of child array.

Any thoughts?

6
  • 2
    Well I would suggest you give it a try and then ask for help if you cannot get it to work Commented Jul 31, 2017 at 9:57
  • give it a try DrKey Commented Jul 31, 2017 at 9:58
  • is the reason just to try or learn other ways to do things? Because the array_map would need approx. a comparable char count than a loop. (you can write such loops in one line too) Commented Jul 31, 2017 at 10:00
  • 3
    call_user_func_array('array_merge',$array) Commented Jul 31, 2017 at 10:00
  • 1
    I don't think a downvote would be necessary, just ask.. Commented Jul 31, 2017 at 10:00

2 Answers 2

2

PHP 5.6 introduce the variadic functions in PHP, which allow one to write funtions that take any additional argument into the same array using the splat operator : ... .

The other - maybe fairly less known - use of that operator is that it works the other way around. By placing that operator before an array in a function's call, it makes that function to take the entries of that array as if you wrote them inline.

Which allows you to type :

$array = array_merge(... $array);

Sending $array would usually return $array unchanged. Using the splat makes array_merge to work on the undefined amount of 2nd level arrays in it. Since array_merge is itself a variadic function that merge any arrays you send to it, it works.

Sign up to request clarification or add additional context in comments.

1 Comment

Amazing, I didn't even know the splat operator.. Thank you so much!
1

try this: made it work with array_reduce.

$result = array_reduce($array, function($final, $value) {
    return array_merge($final, $value);
}, array());

online example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.