Easiest way to implode() a two-dimensional array?

后端 未结 7 1688
眼角桃花
眼角桃花 2020-12-16 11:26

I\'m new to PHP, and don\'t have quite the grip on how it works. If I have a two dimensional array as such (returned by a database):

array(3) {   
    [0]=&         


        
7条回答
  •  独厮守ぢ
    2020-12-16 12:18

    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
    

提交回复
热议问题