Be aware that if one of your result fields is an array, it will be output as a string using the general format of '{value1,value2, ... }' in accordance with postgres's behavior with SQL arrays.
http://www.postgresql.org/docs/8.4/static/arrays.html#ARRAYS-IO
So, here is a function to convert simple (one-dimensional) SQL arrays to PHP arrays:
<?php
function pg_parse_array($field)
/*
* Converts a simple SQL array field to its PHP equivalent. e.g:
*
* {null} --> Array(null);
* {"null"} --> Array("null");
* {foo,bar} --> Array("foo", "bar");
* {"foo,bar"} --> Array("foo,bar");
* {"Hello \"World\""} --> Array('Hello "World"');
*
*/
{
// NULL fields are always NULL
if (!is_string($field)) return $field;
// Check for curly braces which may indicate an SQL array field
if ($field[0] != '{' or substr($field, -1) != '}') return $field;
$field = trim(substr($field, 1, -1));
$array = Array();
// Break up the string into the following:
// - quoted text that MAY have special chars escaped by a backslash
// - unquoted text that may NOT have special chars
$search = '/(")?+((?(1)(?:\\\\.|[^"])*|[^,]+))(?(1)\\1)/';
preg_match_all($search, $field, $matches, PREG_SET_ORDER);
foreach($matches as $value)
{
if ($value[1])
{
// Quoted element, with backslash used to escape chars
$array[] = preg_replace('#\\\\(.)#', '$1', $value[2]);
}
else
{
// Unquoted element
$value[2] = trim($value[2]);
if (strtolower($value[2]) == 'null') $array[] = null; // NULL
else $array[] = $value[2];
}
}
return $array;
}
// Some tests to demonstrate this function
var_export(pg_parse_array('{null}'); // Output is Array(null);
var_export(pg_parse_array('{foo,bar}'); // Output is Array('foo', 'bar');
var_export(pg_parse_array('{"null"}'); // Output is Array('null');
?>