Has anyone come up with a good solution for converting an array to a Postgres HStore Values?
Pomms Converter, https://github.com/chanmix51/Pomm/blob/master/Pomm/Converter/PgHStore.php, does not work with multi-dimensional arrays.
If you're interested in converting a PHP array to a PostgreSQL Hstore Array (data type: hstore[]), then PHPG's Utils class does the trick (disclaimer: I'm the maintainer of that project):
PHP Array of Associative Arrays to PostgreSQL Hstore Array:
<?php
include 'phpg_utils.php';
$array = array(
array(
'name' => 'John',
'age' => 32
),
array(
'name' => 'Jane',
'age' => 28
)
);
$hstore_array = PHPG_Utils::hstoreFromPhp($array, True);
print $hstore_array;
// Outputs:
// {"\"name\"=>\"John\",\"age\"=>\"32\"","\"name\"=>\"Jane\",\"age\"=>\"28\""}
// You can then directly insert this into the database:
pg_query("INSERT INTO my_table (hstore_arr_col) VALUES ('" . pg_escape_string($hstore_array) . "')");
PHP Associative Array to PostgreSQL Hstore:
$array = array(
'name' => 'John',
'age' => 32
);
$hstore = PHPG_Utils::hstoreFromPhp($array);
print $hstore ;
// Outputs:
// "name"=>"John","age"=>"32"
// You can then directly insert this into the database:
pg_query("INSERT INTO my_table (hstore_col) VALUES ('" . pg_escape_string($hstore) . "')");
UPDATE:
In a PostgreSQL 9.4+ world, I'd highly recommend using PostgreSQL's JSONB data-type rather than HSTORE. This allows you to easily encode PHP associative arrays to JSON, and vice versa. This means no special libraries, and official support across the board.