Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 532
SomeKittens Avatar asked Jun 14 '12 17:06

SomeKittens


People also ask

How do you implode an array of arrays?

You could create a temporary array with the required values, then implode the contents. $deviceIds = array(); foreach ($multiDimArray as $item) { $deviceIds[] = $item['device_id']; } $str = implode(',', $deviceIds);

What is the first parameter of the implode () function?

The first parameter is 'separator' The separator is the optional parameter, and it is there to specify what is needed to be put between the array components. By default, it appears as ”, “ which denotes an empty string. The array values are joined to form a string and are separated by the separator parameter.

Can you create a 2 dimensional array with different types?

You can have multiple datatypes; String, double, int, and other object types within a single element of the arrray, ie objArray[0] can contain as many different data types as you need. Using a 2-D array has absolutely no affect on the output, but how the data is allocated.


1 Answers

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

like image 88
Paul Avatar answered Oct 02 '22 06:10

Paul