Are there any functions for recursively exploding and imploding multi-dimensional arrays in PHP?
4 Answers
You can do this by writing a recursive function:
function multi_implode($array, $glue) {
$ret = '';
foreach ($array as $item) {
if (is_array($item)) {
$ret .= multi_implode($item, $glue) . $glue;
} else {
$ret .= $item . $glue;
}
}
$ret = substr($ret, 0, 0-strlen($glue));
return $ret;
}
As for exploding, this is impossible unless you give some kind of formal structure to the string, in which case you are into the realm of serialisation, for which functions already exist: serialize, json_encode, http_build_query among others.
I've found that var_export is good if you need a readable string representation (exploding) of the multi-dimensional array without automatically printing the value like var_dump.
1 Comment
print_r is similar php.net/manual/en/function.print-r.phpYou can use array_walk_recursive to call a given function on every value in the array recursively. How that function looks like depends on the actual data and what you’re trying to do.
Comments
I made two recursive functions to implode and explode.
The result of multi_explode may not work as expected (the values are all stored at the same dimension level).
function multi_implode(array $glues, array $array){
$out = "";
$g = array_shift($glues);
$c = count($array);
$i = 0;
foreach ($array as $val){
if (is_array($val)){
$out .= multi_implode($glues,$val);
} else {
$out .= (string)$val;
}
$i++;
if ($i<$c){
$out .= $g;
}
}
return $out;
}
function multi_explode(array $delimiter,$string){
$d = array_shift($delimiter);
if ($d!=NULL){
$tmp = explode($d,$string);
foreach ($tmp as $key => $o){
$out[$key] = multi_explode($delimiter,$o);
}
} else {
return $string;
}
return $out;
}
To use them:
echo $s = multi_implode(
array(';',',','-'),
array(
'a',
array(10),
array(10,20),
array(
10,
array('s','t'),
array('z','g')
)
)
);
$a= multi_explode(array(';',',','-'),$s);
var_export($a);
['foo'=>['bar'=>1, 'baz'=>[2,3]]]and will return a string like{"foo":{"bar":1,"baz":[2,3]}}. json_decode can then return the JSON-encoded string as an object. JSON data comes handy when passing data from PHP to Javascript as JSON (stdClass Object ( [foo] => stdClass Object ... }).function multi_implode($glue,$array) { $out = ""; foreach ($array as $item) { if(is_array($item)){ if(empty($out)) $out=multi_implode($glue,$item); else $out.=$glue.multi_implode($glue,$item); }else{ if(empty($out)) $out=$item; else $out.=$glue.$item; } } return $out; }