Reputation:
I am trying to turn a multidimensional array into a patterned string with this array_map
function:
function array_to_string($array) {
return implode("&",array_map(function($a){return implode("~",$a);},$array));
}
$arr = array("hello",array("blue","red"),array("one","three","twenty"),"random");
array_to_string($arr);
Between each array element "&" and between each sub-array element (if it is an array) "~"
Should Output: hello&blue~red&one~three~twenty&random
However this outputs: Warning: implode(): Invalid arguments passed
(2)
I tried changing the function within the array_map
to detect whether the multi-array's value is_array
but from my outputs, I don't think that is possible? So essentially, I guess the real question is how can I place a test on the array_map
function to see whether or not it is_array
Upvotes: 0
Views: 127
Reputation: 9056
Since $a can be an array or a string, you should check it in your callback function:
function array_to_string($array) {
return implode("&",
array_map(function($a) {
return is_array($a) ? implode("~",$a) : $a;
}, $array)
);
}
Upvotes: 2