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
.
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);
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With