note 95693 added to function.pg-fetch-assoc

From: Date: Sat, 16 Jan 2010 11:16:13 +0000
Subject: note 95693 added to function.pg-fetch-assoc
Groups: php.notes 
Request: Send a blank email to php-notes+get-165023@lists.php.net to get a copy of this message
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'); ?> ---- Server IP: 64.71.164.2 Probable Submitter: 67.237.232.160 ---- Manual Page -- http://www.php.net/manual/en/function.pg-fetch-assoc.php Edit -- https://master.php.net/note/edit/95693 Del: integrated -- https://master.php.net/note/delete/95693/integrated Del: useless -- https://master.php.net/note/delete/95693/useless Del: bad code -- https://master.php.net/note/delete/95693/bad+code Del: spam -- https://master.php.net/note/delete/95693/spam Del: non-english -- https://master.php.net/note/delete/95693/non-english Del: in docs -- https://master.php.net/note/delete/95693/in+docs Del: other reasons-- https://master.php.net/note/delete/95693 Reject -- https://master.php.net/note/reject/95693 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#165023) next »