Multidimensional Array to String
Saving the imploded inner arrays to an array. Then imploding those.
(written in the spirit of your original implementation)
function convert_multi_array($arrays)
{
$imploded = array();
foreach($arrays as $array) {
$imploded[] = implode('~', $array);
}
return implode("&", $imploded);
}
Look at my version. It implodes any dimension:
function implode_all($glue, $arr){
for ($i=0; $i<count($arr); $i++) {
if (@is_array($arr[$i]))
$arr[$i] = implode_all ($glue, $arr[$i]);
}
return implode($glue, $arr);
}
Here is the example:
echo implode_all(',',
array(
1,
2,
array('31','32'),
array('4'),
array(
array(511,512),
array(521,522,523,524),
53))
);
Will print:
1,2,31,32,4,511,512,521,522,523,524,53
I tried a bunch of these, but non of them ticked all the boxes for me. The one that came the closes was Jeff_Alieffsons.
Here is an adjusted version, where you can chuck whatever multidimensional array into it, and then it'll return a string.
function implode_all( $glue, $arr ){
if( is_array( $arr ) ){
foreach( $arr as $key => &$value ){
if( @is_array( $value ) ){
$arr[ $key ] = implode_all( $glue, $value );
}
}
return implode( $glue, $arr );
}
// Not array
return $arr;
}
You are overwriting $array
, which contains the original array. But in a foreach
a copy of $array
is being worked on, so you are basically just assigning a new variable.
What you should do is iterate through the child arrays and "convert" them to strings, then implode the result.
function convert_multi_array($array) {
$out = implode("&",array_map(function($a) {return implode("~",$a);},$array));
print_r($out);
}