PHP array_map for multidimensional arrays

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.

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().

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.

0 0 vote
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Kevin
Kevin
3 years ago

$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

arjun
3 years ago
Reply to  Kevin

Just updated the post, there was a typo, just replace $funcion with $function

DMCA.com Protection Status
2
0
Would love your thoughts, please comment.x
()
x