Implode two-dimensional array in PHP

2020-04-21 05:37发布

问题:

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?

回答1:

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



回答2:

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);


回答3:

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