0

I have an array from a SQL query which looks like this:

array(2) { 
[0]=> array(2) { ["ID"]=> string(1) "a" [0]=> string(1) "a" } 
[1]=> array(2) { ["ID"]=> string(1) "b" [0]=> string(1) "b" } } 

I want to turn it into a list, so it looks like this:

'a','b'

I've tried various methods from around the site/google, but can't seem to get anything working. They include:

implode(',',$arr);   

$list='';
foreach($arr as $row){
$list=$list+$row['ID'];
}
3
  • 3
    What all methods have you already tried but failed? Commented Aug 22, 2013 at 13:16
  • 1
    Start by modifying your SQL query call so that it returns either an associative or an enumarated array, but not both Commented Aug 22, 2013 at 13:25
  • yes, noted, I've altered the fetch statement to $res = $stmt->fetchAll(PDO::FETCH_ASSOC); makes the array much easier to work with Commented Aug 22, 2013 at 13:32

2 Answers 2

4

First, turn your array into an array, containing only the IDs with quotemarks around them (array_map), then join them together with a comma (join):

echo join(', ', array_map(
  function($item) { return "'" . $item['ID'] . "'"; },
  $your_array));
Sign up to request clarification or add additional context in comments.

3 Comments

Note that join is now an alias of implode so you should use implode directly.
@Technoh: yes, they both perform the same operation, so I don't see any advantage of using one over the other.
Have accepted this because, a. it was first and b. the explanation meant I understood how the answer worked. Thanks
0

Try following


$test = "'".implode("','",$arr)."'";

for assoc array try


$test = "'".implode("','",array_map_assoc(function($k,$v){return "$v";},$arr))."'";

2 Comments

I tried that before, doesn't work... Array to string conversion
check for assoc array. Also see this post stackoverflow.com/questions/6556985/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.