Array map is one of the interesting PHP’s array function. But it will not work with multidimensional arrays as expected.So in this post, I would like to share a simple alternative technique for array_map(). Our function will work like array_map but it will support multidimensional arrays.
1 2 3 4 5 6 7 8 9 |
function my_array_map($function, $arrary) { $result = array(); foreach ($arr as $key => $val) { $result[$key] = (is_array($val) ? my_array_map($function, $val) : $function($val)); } return $result; } |
Here we used recursive function methodology and the Ternary Operator syntax.
How to use
you can use my_array_map just like as array_map().
1 2 |
$array = array('test ',array('website' => 'arjun php ')); my_array_map('trim',$array); |
That’s it.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
$value=array(
“result”=>$str,
“rightAnswer”=>$arr,
“tid”=>$topicId,
“view”=>$view,
);
//$value = array_map(‘utf8_encode’, $value);
function my_array_map($funcion, $value)
{
$result = array();
foreach ($value as $key => $val)
{
$result[$key] = (is_array($val) ? my_array_map($function, $val) : $function($val));
}
return $result;
}
my_array_map(‘utf8_encode’,$value);
echo json_encode($value);
this shows $function is undefined
Just updated the post, there was a typo, just replace $funcion with $function