87

I'm a novice at PHP and I need a quick solution to the following problem but can't seem to come up with one:

I have a multi-dimensional array like so

Array
(
    [0] => Array
        (
            [blogTags_id] => 1
            [tag_name] => google
            [inserted_on] => 2013-05-22 09:51:34
            [inserted_by] => 2
        )

    [1] => Array
        (
            [blogTags_id] => 2
            [tag_name] => technology
            [inserted_on] => 2013-05-22 09:51:34
            [inserted_by] => 2
        )
)

I want to use the implode() to somehow return a comma-separated string containing values of tag_name key like so.

google, technology

Is it possible to achieve this effect with the said function? If not then please suggest an alternate solution.

liamvictor
  • 3,251
  • 1
  • 22
  • 25
CobaltBabyBear
  • 2,188
  • 6
  • 26
  • 47

7 Answers7

201

Quite simple:

$input = array(
  array(
    'tag_name' => 'google'
  ),
  array(
    'tag_name' => 'technology'
  )
);

echo implode(', ', array_map(function ($entry) {
  return $entry['tag_name'];
}, $input));

http://3v4l.org/ltBZ0


and new in php v5.5.0, array_column:

echo implode(', ', array_column($input, 'tag_name'));
Yoshi
  • 54,081
  • 14
  • 89
  • 103
19

Although this question is related to string conversion, I stumbled upon this while wanting an easy way to write arrays to my log files. If you just want the info, and don't care about the exact cleanliness of a string you might consider:

json_encode($array)
Msencenb
  • 5,675
  • 11
  • 52
  • 84
10

array_map is a call back function, where you can play with the passed array. this should work.

$str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));
kamal pal
  • 4,187
  • 5
  • 25
  • 40
Farhan
  • 1,561
  • 14
  • 12
8
join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))
deceze
  • 510,633
  • 85
  • 743
  • 889
7

very simple go for this

$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma 
Vigneswaran S
  • 2,039
  • 1
  • 20
  • 32
3

If you want "tag_name" with associated "blogTags_id" use: (PHP > 5.5)

$blogDatas = array_column($your_multi_dim_array, 'tag_name', 'blogTags_id');
echo implode(', ', array_map(function ($k, $v) { return "$k: $v"; }, array_keys($blogDatas), array_values($blogDatas)));
Tarik
  • 4,270
  • 38
  • 35
1

In this situation implode($array,','); will works, becasue you want the values only. In PHP 5.6 working for me.

If you want to implode the keys and the values in one like :
blogTags_id: 1
tag_name: google

$toImplode=array();
foreach($array as $key => $value) {
$toImplode[]= "$key: $value".'<br>';
}
$imploded=implode('',$toImplode);

Sorry, I understand wrong, becasue the title "Implode data from a multi-dimensional array". Well, my answer still answer it somehow, may help someone, so will not delete it.

Atanas Atanasov
  • 203
  • 1
  • 4