DB_Pgsql_Type is a framework for converting complex PostgreSQL 8.3+ types to their PHP counterparts and vice versa. With it, you can work with fields of a complex type (for example, a two-dimensional array of composite types) as easy as with familiar PHP arrays.
The following data types and any of their nested combinations are supported:
- Arrays of elements of arbitrary type (including multidimensional).
- Composite types and ROWTYPE (in particular, they themselves contain composite fields or array fields).
- Hstore (including those containing complex elements).
- Other types: TIMESTAMP (converted to Unix time), DATE, TIME, BOOLEAN, etc.
PostgreSQL is famous for its support for complex data types. For example, you can define a column of a table as a two-dimensional array of strings:
CREATE TABLE something (
id intEGer
matrix TEXT [] []
);
INSERT INTO something (id, matrix) VALUES (
1, ARRAY [ARRAY ['one', 'two'], ARRAY ['three "3"', 'four']]
);
However, in a PHP script, when trying to get a value from such a column:
')
$ rs = $ pdo-> query ("SELECT matrix FROM something WHERE id = 1");
echo $ rs-> fetchColumn ();
you will see only a string representation of this data, something like:
{{one, two}, {"three \" 3 \ "", four}}
DB_Pgsql_Type allows you to convert expressions of the form {{one, two}, {"three \" 3 "", four}} into a two-dimensional PHP array (taking into account the features of quoting of special sequences: quotes, apostrophes, empty strings, NULL and etc.) Or vice versa, if you need to write a two-dimensional array in the database.
Library sources and documentation can be found here:
dklab.ru/lib/DB_Pgsql_TypeHere as the simplest example, here’s the code to parse a two-dimensional array of strings from the listing above:
// Create a parser for the type "array of arrays of strings".
$ parser = new DB_Pgsql_Type_Array (
new DB_Pgsql_Type_Array (
new DB_Pgsql_Type_String ()
)
);
// Returns array (array ("one", "two"), array ('three "3"', "four"))
$ array = $ parser-> input ('$ Blk {' one, two}, {"three \" 3 \ "", four '}');
You can build back a string on a PHP array to insert into the database:
echo $ parser-> output ($ array);
Download the library and see other examples : working with arrays, composite types and ROWTYPE, hstore, etc.