php array walk recursive code example
Example 1: array_walk_recursive get return value
Flatten multidimensional associative array to array
function flatten(array $array, $prefix="") {
$result = Array();
array_walk($array, function ($value, $key) use ($array, $prefix, &$result) {
$path = $prefix ? "$prefix.$key" : $key;
if (is_array($value)) {
$result = array_merge($result, flatten($value, $path));
} else {
$result[$path] = $value;
}
});
return $result;
}
print_r(flatten($arrr));
from site:
https://stackoverflow.com/questions/39071537/array-walk-recursive-to-return-array-name-rather-than-index-number
Example 2: php array walk recursive
<?php
/*
* Two Dimensional Arrays:- array_walk_recursive() function is used
**/
$alphabets = array(
'a' => 'apple',
'b' => 'ball',
'c' => 'cat',
array(
'd' => 'dog',
'e' => 'elephant',
)
);
array_walk_recursive($alphabets, 'myFunc2', 'for' );
function myFunc2($value, $key, $param){
echo "$key $param $value <br>";
};
?>
/*
Out Put
a for apple
b for ball
c for cat
d for dog
e for elephant
*/
Example 3: php array_walk_recursive
$arr = array(1, array(2, 3));
// Call function on every item, even subarrays.
// Sign $item as reference to work on original item.
array_walk_recursive($arr, function(&$item, $key, $myParam){
$item *= 2;
}, 'will be in myParam');
// $arr now is [2, [4, 6]]