Implode two-dimensional array in PHP

浪尽此生 提交于 2019-12-02 07:38:41

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

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!