2

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

4
$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)

Sign up to request clarification or add additional context in comments.

5 Comments

Don't think there is a need to confuse beginner PHP programmers with constructions of such complexity.
@Fra Seriously? This is "complex"?
Yes. Closures is not something beginners can understand very well.
@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?
Do you see the level of the question asked? The guy doesn't know how to restructure a given array. Forget Scheme. ;)
1
$resultArray = array();
foreach($myNestedArray as $item) {
   $resultArray[]=$item['user_id'];
}
$resultString = implode(',', $resultArray);

Works on all recent PHP versions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.