M.Stark
M.Stark

Reputation: 37

PHP PostgreSQL array to string

I have a problem in my PHP script that uses PostgreSQL for fetching and storing data.

Currently I am using the following code:

 $q = "SELECT id FROM playlisty WHERE id_profilu=1;";
 $r = pg_query($q);
 $arr = pg_fetch_all($r);
 echo '<pre>'; var_dump($arr); echo'</pre>';

The output generated by the above code snippet:

array(4) {
  [0]=>
  array(1) {
    ["id"]=>
    string(4) "2014"
  }
  [1]=>
  array(1) {
    ["id"]=>
    string(4) "1549"
  }
  [2]=>
  array(1) {
    ["id"]=>
    string(4) "1965"
  }
  [3]=>
  array(1) {
    ["id"]=>
    string(4) "2047"
  }
}

However, I would prefer if the output looked something like the following: 2014, 1549, 1965, 2047 (i.e. a simple array of id-s of certain playlists). I also tried using implode (to no anvil), and got Array,Array,Array,Array as a reply.

Upvotes: 1

Views: 794

Answers (4)

Vin.AI
Vin.AI

Reputation: 2437

Do select like this:

$q = "SELECT array_to_string(id, ',') AS id FROM playlisty WHERE id_profilu=1 ";

Upvotes: 0

Why not just loop it ?

$str=""; 
foreach($yourarr as $arr) 
{ 
    $str.=implode(',',$arr).',';
} 
echo rtrim($str,','); //"prints" 2014, 1549, 1965, 2047

Upvotes: 1

hindmost
hindmost

Reputation: 7205

Add this line before echo:

$arr = array_map(function ($v) { return $v['id']; }, $arr);

If you want to output result as string then you have to use implode function. Replace last line with this:

echo '<pre>'. implode(', ', $arr). '</pre>';

Upvotes: 1

HarryIsBack
HarryIsBack

Reputation: 40

Try this:

$array = array(
            0=>array('id'=>"2014"),
            1=>array('id'=>"2015"),
            2=>array('id'=>"2016"),
        );
        $ids = array_map(function($item) { return $item['id']; }, $array);
        $result = implode($ids,',');
        var_dump($result);

Output: string '2014,2015,2016' (length=14)

Upvotes: 0

Related Questions