0

Using the following code, I expect a comma delimited string from the implode:

$result = pg_exec($this->db, $sql);
$rows = pg_fetch_all($result);
$indexlistids = implode(", ", $rows);
echo $indexlistids."<br />";

But I get this: Notice: Array to string conversion and it echos Array

Got the same results using
$indexlistids = join(", ", $rows);

It looks correct, what exactly am I doing wrong here?

MB34
  • 4,210
  • 12
  • 59
  • 110

1 Answers1

0

$rows is an array of arrays. The "Array to string conversion" error come from the fact that the elements inside $rows are arrays, not a strings.

By example, implode(', ', reset($rows)) should work, but will not show the expected result.

You could use array_column() to extract your identifiers before to use implode():

$result = pg_exec($this->db, $sql);
$rows = pg_fetch_all($result);
$ids = array_column($rows, 'id'); // 'id' should be the name of your column or alias
$indexlistids = implode(", ", $ids);
echo $indexlistids."<br />";

Example:

$array = [ ['id'=>2,'val'=>'foo'], ['id'=>3,'val'=>'bar'] ];
$str = implode(', ', $array); // Array to string conversion
$str = implode(', ', array_column($array, 'id')); // Works
Syscall
  • 19,327
  • 10
  • 37
  • 52