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]=&
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;
}
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"));
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
// simplest
$str = implode(',',array_map('implode',$arr));
One line command
implode(',', array_map('implode', $arr, array_fill(0, count($arr), '')))
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