Chris Otaalo
Chris Otaalo

Reputation: 151

How can I implode() a multidimensional array to a string?

I am trying to implode this multidimensional array into a string:

$smile = Array ( 
    [a] => Array ( [0] => "smile") 
    [b] => Array ( [0] => "cat"   [1] => "dog") 
    [c] => Array ( [0] => "ora"   [1] => "rita") 
    [d] => Array ( [0] => "miley" [1] => "cyrus") 
)

I would like it to be in a list like this:

smile, cat, dog, ora, rita, miley, cyrus

How could I go about it?

Upvotes: 0

Views: 170

Answers (1)

Claudio Venturini
Claudio Venturini

Reputation: 698

If the array has no other levels of arrays nested, I would first implode all nested arrays with a single for loop, and then implode. Like this:

for ($i = 0; $i < count($smile); $i++){
    if (is_array($smile[$i])){
        $smile[$i] = implode($smile[$i], ',');
    }
}

$result = implode($smile, ',');

If you don't know how many levels of nesting could be, you can use recursion. For example something like this should work:

function collapse($array, $glue = ','){
    for ($i = 0; $i < count($array); $i++){
        if (is_array($array[$i])){
            $array[$i] = collapse($array[$i], $glue);
        }
    }

    return implode($array, $glue);
}

$imploded = collapse($smile, ',');

Upvotes: 2

Related Questions