1

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.

2
  • HStores are a 1 dimension key => value stores, there are, afaik, no way to store multidimensional arrays in them unless you serialize them as strings (loosing all way to search in them in the db btw). Why do you want to convert an array into a HStore ? Commented Jan 23, 2013 at 9:46
  • he might be referring to hstore arrays: hstore[] data types. Commented Apr 11, 2013 at 19:57

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.