PHP reset first level of array without loop
I have a simple multidimensional array like
$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 next
$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 this is pretty easy with a loop foreach
to achieve, but I'm wondering if it can be done with one line code.
What I have tried so far
array_map('key', $array);
but it only returns the first key of the child array.
Any thoughts?
source to share
PHP 5.6 introduces variable functions in PHP, which allows you to write functions that take any additional argument into the same array using the splat: operator ...
.
Another - perhaps lesser known - use of this operator is that it works the other way around. By placing this operator in front of an array in a function call, it makes that function accept the entries of that array as if you had written them in a string.
Allows you to enter:
$array = array_merge(... $array);
Sending a $ array will usually return the $ array unchanged. Using splat allows you to array_merge
work with the number of undefined 2nd level arrays in it. Since array_merge is itself a variation function that concatenates whatever arrays you send to it, it works.
source to share