I'm working with PostgreSQL's HSTORE data type and PHP.
I require the ability to transform PostgreSQL's returned hstore string into a PHP array. I've tried using the fromPg() method defined here as mentioned in [this post][2], however when I save the value and attempt to retrieve it, when I encounter a value similar to the following:
"myKey" => "my\"Value"
... the fromPg() method breaks the value into two array entries, the first having a key of "myKey" and a value of "my\" and the second having a key of "Value\"" and a blank value.
I'm wondering if anyone else has had this problem and if someone would be willing to provide a more functional method of transforming an hstore string into it's equivalent PHP array.
Here is a code sample to replicate the issue I'm having with the existing "solution":
<?php
function fromPg($data) {
$split = preg_split('/[,\s]*"([^"]+)"[,\s]*|[,=>\s]+/', $data, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$hstore = array();
for($index = 0; $index < count($split); $index = $index + 2) {
$hstore[$split[$index]] = $split[$index + 1] != 'NULL' ? $split[$index + 1] : null;
}
return $hstore;
}
$hstore_string = '"myKey" => "my\"Value"';
$hstore_array = fromPg($hstore_string);
print '<pre>';
print_r($hstore_array);
print '</pre>';
I've finally broken down and created a PHP library of my own specifically designed to tackle this problem, as well as many other shortcomings of PHP's PostgreSQL driver such as automatic detection and transformation of PostgreSQL Hstores, Arrays, Dates, Geometric data-types, etc. It's available on GitHub at: https://github.com/JDBurnZ/PHPG