Implode two-dimensional array in PHP

扶醉桌前 提交于 2019-12-20 04:26:19

问题


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


来源:https://stackoverflow.com/questions/27078892/implode-two-dimensional-array-in-php

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