Home >Database >Mysql Tutorial >How to Zip Two Arrays in PostgreSQL to Create a Multi-Dimensional Array?
There are several methods to combine two arrays into a single multidimensional array using Postgres functions:
Postgres 9.5 or later:
Postgres 9.4:
Postgres 9.3 or older:
Consider the following example for Postgres 9.3 or earlier:
SELECT ARRAY[a,b] AS ab FROM ( SELECT unnest('{a,b,c}'::text[]) AS a , unnest('{d,e,f}'::text[]) AS b ) x;
Result:
ab ------- {a,d} {b,e} {c,f}
To aggregate the resulting set of arrays into a 2-dimensional array, a custom aggregate function called array_agg_mult() is needed:
CREATE AGGREGATE array_agg_mult (anyarray) ( SFUNC = array_cat , STYPE = anyarray , INITCOND = '{}' );
Then, use it as follows:
SELECT array_agg_mult(ARRAY[ARRAY[a,b]]) AS ab FROM ( SELECT unnest('{a,b,c}'::text[]) AS a , unnest('{d,e,f}'::text[]) AS b ) x;
Result:
{{a,d},{b,e},{c,f}}
The above is the detailed content of How to Zip Two Arrays in PostgreSQL to Create a Multi-Dimensional Array?. For more information, please follow other related articles on the PHP Chinese website!