问题
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.
回答1:
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'));
回答2:
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)
回答3:
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));
回答4:
join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))
回答5:
very simple go for this
$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma
回答6:
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)));
回答7:
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.
来源:https://stackoverflow.com/questions/16710800/implode-data-from-a-multi-dimensional-array