22

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]=> array(1) {         
        ["tag_id"]=> string(1) "5" 
    } 
    [1]=> array(1) {         
        ["tag_id"]=> string(1) "3" 
    } 
    [2]=> array(1) {         
        ["tag_id"]=> string(1) "4" 
    } 
}

and want to turn it into the string 5,3,4 what would be the quickest way do do this? I currently have an obnoxious foreach loop, but was hoping it could be done in one line. A standard implode gives me Array,Array,Array.

SomeKittens
  • 38,868
  • 19
  • 114
  • 143
  • 3
    You can remove all the line breaks in your `foreach`. – Alex Turpin Jun 14 '12 at 17:28
  • What I'm trying to say is that you shouldn't care if something uses a couple of lines. – Alex Turpin Jun 14 '12 at 17:28
  • 1
    @Xeon06 While I agree on principle, I'd like to see if there's a nifty way to do it better. Half of this project is learning, the other half is actual coding. (Even better, I could remove all the line breaks and tell my boss that the code only needed a one-liner) – SomeKittens Jun 14 '12 at 17:33

7 Answers7

33

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

Paul
  • 139,544
  • 27
  • 275
  • 264
  • 1
    Well, you can actually pass the result of `array_map` right into `implode` call. ) – raina77ow Jun 14 '12 at 17:33
  • @raina77ow Yes, but I think it might be better to modify the original array since the extra dimension seems useless. I'll update my answer though :) – Paul Jun 14 '12 at 17:34
8

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
Bruce Lim
  • 745
  • 6
  • 22
7
// simplest
$str = implode(',',array_map('implode',$arr));
Scot Nery
  • 671
  • 7
  • 19
6

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")); 
apokryfos
  • 38,771
  • 9
  • 70
  • 114
3

One line command

implode(',', array_map('implode', $arr, array_fill(0, count($arr), '')))
Loc Nguyen
  • 356
  • 3
  • 6
2

Check out the below from the PHP implode() manual:

<?php
/**
 * Implode an array with the key and value pair giving
 * a glue, a separator between pairs and the array
 * to implode.
 * @param string $glue The glue between key and value
 * @param string $separator Separator between pairs
 * @param array $array The array to implode
 * @return string The imploded array
 */
function array_implode( $glue, $separator, $array ) {
    if ( ! is_array( $array ) ) return $array;
    $string = array();
    foreach ( $array as $key => $val ) {
        if ( is_array( $val ) )
            $val = implode( ',', $val );
        $string[] = "{$key}{$glue}{$val}";

    }
    return implode( $separator, $string );

}
?>

If you only want to return the value (and not the key), just modify the above to use $string[] = "{$val}";.

hannebaumsaway
  • 2,644
  • 7
  • 27
  • 37
0
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;
}
RafaSashi
  • 16,483
  • 8
  • 84
  • 94