I am trying to convert a multidimensional array into a string with a particular format.
function convert_multi_array($array) {
foreach($array as $value)
Here is a simple answer:
function implode_recur ($separator, $arrayvar){
$output = "";
foreach ($arrayvar as $av)
{
if (is_array ($av))
{
$output .= implode_r ($separator, $av);
}
else
{
$output .= $separator.$av;
}
return $output;
}
}
$result = implode_recur(">>",$variable);
Okay happy coding!
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
May be of no interest, but i needed to report a nested array which contained errors, so i simply defined an variable and then with json_encode put this in my email. One way of converting a array to a string.
You can use this one line array to string code:
$output = implode(", ",array_map(function($a) { return '<a href="'.$a['slug'].'">'.$a['name'].'</a>'; }, $your_array) );
print_r($output);
Output:
Link1, Link2, Link3
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);
}
You also can just take the original implementation from the PHP join manual (http://php.net/manual/en/function.join.php)
function joinr($join, $value, $lvl=0)
{
if (!is_array($join)) return joinr(array($join), $value, $lvl);
$res = array();
if (is_array($value)&&sizeof($value)&&is_array(current($value))) { // Is value are array of sub-arrays?
foreach($value as $val)
$res[] = joinr($join, $val, $lvl+1);
}
elseif(is_array($value)) {
$res = $value;
}
else $res[] = $value;
return join(isset($join[$lvl])?$join[$lvl]:"", $res);
}
$arr = array(array("blue", "red", "green"), array("one", "three", "twenty"));
joinr(array("&", "~"), $arr);
This is recursive, so you even can do
$arr = array(array("a", "b"), array(array("c", "d"), array("e", "f")), "g");
joinr(array("/", "-", "+"), $arr);
and you'll get
a-b/c+d-e+f/g