note 40879 deleted from ref.pgsql by aidan
| From: | aidan@php.net | Date: | Wed, 01 Dec 2004 07:21:58 +0000 |
| Subject: | note 40879 deleted from ref.pgsql by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-81212@lists.php.net to get a copy of this message | ||
Note Submitter:
----
I wrote some code that converts Postgres arrays to PHP arrays. I haven't done too much
testing, but it seems to do the job for me.
/**
* A quick and dirty array grabber for postgres arrays. Not
* tested very well.
* @returns A PHP array.
**/
function toArray($pgArray){
if(strlen($pgArray) == 0){
return;
}
elseif($this->getChar($pgArray) == "," or $this->getChar($pgArray) == "
"){
return $this->toArray(substr($pgArray, 1));
}
elseif($this->getChar($pgArray) == "{"){
//find the end of the array
$depth = 1;
for($i=1; $depth>0 && $i<strlen($pgArray); $i++){
if($this->getChar($pgArray, $i) == '\\'){
//skip escape chars
$i++;
next;
}
if($this->getChar($pgArray, $i) == "{"){
$depth++;
next;
}
if($this->getChar($pgArray, $i) == "}"){
$depth--;
next;
}
}
$arrayEnd = $i;
$first = substr($pgArray, 1, $arrayEnd - 2);
$second = substr($pgArray, $arrayEnd);
if($second == ""){
return $this->toArray($first);
}
$r[] = $this->toArray($first);
$r[] = $this->toArray($second);
return $r;
}
elseif($this->getChar($pgArray) == "\""){
//a quoted item
$depth = 1;
for($i=1; $depth && $i<strlen($pgArray); $i++){
if($this->getChar($pgArray, $i) == "\\"){
$i++;
next;
}
if($this->getChar($pgArray, $i) == "\""){
$depth--;
next;
}
}
$arrayEnd = $i;
$r[] = substr($pgArray, 1, $arrayEnd - 2);
$r = array_merge($r,
$this->toArray(substr($pgArray, $arrayEnd + 1)));
return $r;
}
else{
//an unquoted item
$depth = 1;
for($i=1; $depth && $i<strlen($pgArray); $i++){
if($this->getChar($pgArray, $i) == "\\"){
$i++;
next;
}
if($this->getChar($pgArray, $i) == ","){
$depth--;
next;
}
}
$arrayEnd = $i;
if($arrayEnd == strlen($pgArray)){
$r[] = $pgArray;
}
else{
$r[] = substr($pgArray, 0, $arrayEnd-1);
}
$r = array_merge($r,$this->toArray(substr($pgArray,
$arrayEnd)));
return $r;
}
}
function getChar($string, $pos=0){
return substr($string, $pos, 1);
}