I have a result set from a DB that returns the following array.... how do I implode this into a comma delimited string?
Array
(
[0] => Array
(
[user_id] => 2
)
[1] => Array
(
[user_id] => 5
)
[2] => Array
(
[user_id] => 11
)
)
2 Answers 2
$t = array_map(function (array $a) { return $a["user_id"]; }, $original_array);
$result = implode(",", $t);
(PHP 5.3+, the closure must be turned into a regular function for earlier versions)
answered Aug 16, 2010 at 1:59
Artefacto
98.1k17 gold badges207 silver badges232 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Vladislav Rastrusny
Don't think there is a need to confuse beginner PHP programmers with constructions of such complexity.
Artefacto
@Fra Seriously? This is "complex"?
Vladislav Rastrusny
Yes. Closures is not something beginners can understand very well.
Artefacto
@Fra I don't see why.
Scheme is often taught in introductory programming courses. Do you think the beginner PHP programmer cannot understand something a freshman CS undergraduate can?Vladislav Rastrusny
Do you see the level of the question asked? The guy doesn't know how to restructure a given array. Forget Scheme. ;)
$resultArray = array();
foreach($myNestedArray as $item) {
$resultArray[]=$item['user_id'];
}
$resultString = implode(',', $resultArray);
Works on all recent PHP versions.
answered Aug 16, 2010 at 6:49
Vladislav Rastrusny
30.2k23 gold badges100 silver badges158 bronze badges
Comments
lang-php