1

I have an array like:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
        )

    [2] => Array
        (
            [0] => d
            [1] => e
            [2] => f
        )

)

I want to convert my array to a string like below:

$arrtostr = 'a,b,c,d,e,f';

I've used implode() function but it looks like it doesn't work on two-dimensional arrays.

What should I do?

Kevin
  • 41,694
  • 12
  • 53
  • 70
Luvias
  • 563
  • 1
  • 7
  • 19
  • Possible duplicate of [Easiest way to implode() a two-dimensional array?](https://stackoverflow.com/questions/11038282/easiest-way-to-implode-a-two-dimensional-array) – Meloman Sep 05 '17 at 18:49

3 Answers3

4

Alternatively, you could use a container for that first, merge the contents, and in the end of having a flat one, then use implode():

$letters = array();
foreach ($array as $value) {
    $letters = array_merge($letters, $value);
}

echo implode(', ', $letters);

Sample Output

Kevin
  • 41,694
  • 12
  • 53
  • 70
1

Given your subject array:

$subject = array(
    array('a', 'b'),
    array('c'),
    array('d', 'e', 'f'),
);

Two easy ways to get a "flattened" array are:

PHP 5.6.0 and above using the splat operator:

$flat = array_merge(...$subject);

Lower than PHP 5.6.0 using call_user_func_array():

$flat = call_user_func_array('array_merge', $subject);

Both of these give an array like:

$flat = array('a', 'b', 'c', 'd', 'e', 'f');

Then to get your string, just implode:

$string = implode(',', $flat);
salathe
  • 51,324
  • 12
  • 104
  • 132
1

You asked for a two-dimensional array, here's a function that will work for multidimensional array.

function implode_r($g, $p) {
    return is_array($p) ?
           implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) : 
           $p;
}

I can flatten an array structure like so:

$multidimensional_array = array(
    'This',
    array(
        'is',
        array(
            'a',
            'test'
        ),
        array(
            'for',
            'multidimensional',
            array(
                'array'
            )
        )
    )
);

echo implode_r(',', $multidimensional_array);

The results is:

This,is,a,test,for, multidimensional,array
Bruce Lim
  • 745
  • 6
  • 22