Here's my array
$myArr = array(array('one', 'two'), array('one', 'two'));
I would like add an element to every array inside the $myArr. I dont wanna loop over each array inside and add that element. Is there any quicker way to achieve this using array_map or array_walk.. preferably with one line of code?
Result array should be like
$myArr = ar开发者_开发技巧ray(array('one', 'two','three'), array('one', 'two','three'));
Thanks a bunch
Got it, Kudos to @strager
$myvar = 'Three';
$myArr = array_map(function ($subarray) { global $myvar; $subarray[] = $myvar; return $subarray;}, $myArr);
With array_walk
:
array_walk($myArr, create_function('&$subarray', '$subarray[] = "three";'));
With array_map
:
$myArr = array_map(create_function('$subarray', '$subarray[] = "three"; return $subarray;'), $myArr);
With anonymous functions an array_map
(untested; I don't have access to PHP5.3):
$myArr = array_map(function ($subarray) {
$subarray[] = "three";
return $subarray;
}, $myArr);
Or of course, the better solution (for PHP < 5.3):
function pushToEndOfSubarrays($array, $item) {
$ret = array();
foreach ($array as $key => $subarray) {
$subarray[] = $item;
$ret[$key] = $subarray;
}
return $ret;
}
$myArr = pushToEndOfSubarrays($myArr, 'three');
you can use function array_push() for push array into array
int array_push ( array &$array , mixed $var [, mixed $... ] );
This may help you as your requirements.
thanks.
精彩评论