【问题标题】:Convert PHP Multi-Dimensional Array to Postgres HStore将 PHP 多维数组转换为 Postgres HStore
【发布时间】:2013-01-06 11:44:29
【问题描述】:

有没有人想出一个很好的解决方案来将数组转换为 Postgres HStore 值?

Pomms 转换器 https://github.com/chanmix51/Pomm/blob/master/Pomm/Converter/PgHStore.php 不适用于多维数组。

【问题讨论】:

  • HStores 是一维键 => 值存储,有,afaik,没有办法在其中存储多维数组,除非您将它们序列化为字符串(顺便在 db 中搜索它们)。为什么要将数组转换为 HStore ?
  • 他可能指的是 hstore 数组:hstore[] 数据类型。

标签: php arrays postgresql multidimensional-array hstore


【解决方案1】:

如果您有兴趣将 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,反之亦然。这意味着没有特殊的库,以及全面的官方支持。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多