如果您有兴趣将 PHP 数组转换为 PostgreSQL Hstore 数组(数据类型:hstore[]),那么 PHPG's Utils 类就可以解决问题(免责声明:我是该项目的维护者):
关联数组到 PostgreSQL Hstore 数组的 PHP 数组:
<?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 关联数组到 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) . "')");
更新:
在 PostgreSQL 9.4+ 的世界中,我强烈建议使用 PostgreSQL 的 JSONB 数据类型而不是 HSTORE。这使您可以轻松地将 PHP 关联数组编码为 JSON,反之亦然。这意味着没有特殊的库,以及全面的官方支持。