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
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)
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.
join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))
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'));
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));
very simple go for this
$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma