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

后端 未结 7 1595
眼角桃花
眼角桃花 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 11:59
    function recursive_implode($connector=',', $array=[], $implod='keys'){
    
        if($implod=='keys'){
    
            $results=implode($connector,array_keys($array));
        }
        else{
    
            $results=implode($connector,$array);
        }
    
        foreach($array as $key=> $value){
    
            if(is_array($value)){
    
                $results.=$connector.recursive_implode($connector,$value,$implod);
            }
        }
    
        return $results;
    }
    
    0 讨论(0)
  • 2020-12-16 12:01

    If one simply wants to implode a single array "column" as in this case, then the simplest thing to do is:

    implode(",", array_column($array,"tag_id")); 
    
    0 讨论(0)
  • 2020-12-16 12:10

    This modifies your array using array_map, but probably for the better by turning it into a 1D array of tag_id's. Then you can just use implode like normal:

    $arr = array_map(function($el){ return $el['tag_id']; }, $arr);
    $str = implode(',', $arr);
    

    If you don't want to modify your array than you can just do this:

    $str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));
    

    Codepad Demo

    0 讨论(0)
  • 2020-12-16 12:10
    // simplest
    $str = implode(',',array_map('implode',$arr));
    
    0 讨论(0)
  • 2020-12-16 12:12

    One line command

    implode(',', array_map('implode', $arr, array_fill(0, count($arr), '')))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题