Merging two arrays in PostgreSQL as index and value? -


assuming have 2 array fields in table, this:

 column |   type    | --------+-----------+  index  | integer[] |   value  | integer[] |  

where both index , value equal in length, , values in 'index' guaranteed unique, example:

select * arraytest;    index   | value              -----------+-----------------------------------  {1,3,5,6} | {100, 103, 105, 106} 

how make query returns new array, values in 'index' used array indexes, , values in 'value' become values associated given index, i.e. like:

select some_array_function(index, value) newarray;             new_array -------------------------------- {100, null, 103, null, 105, 106} 

what want achieve same array_combine in php.

while overall bad idea store data this, 1 way use unnest function , process results on client side:

select unnest(index), unnest(value) arraytest;   unnest | unnest  --------+--------       1 |    100       3 |    103       5 |    105       6 |    106 

if must have function create new array here's short function it:

create function array_stitch(index_array integer[], value_array integer[]) returns integer[]     language plpgsql immutable     $$ declare     ptr integer;     new_array integer[]; begin     ptr in 1..array_upper(index_array,1) loop             new_array[index_array[ptr]] := value_array[ptr];     end loop;      return new_array; end; $$; 

edit: here's way it:

select array_agg(val order idx) output_array (select generate_series(1,idx[array_upper(idx,1)]) array_test) g(idx) left join (select unnest(idx) idx, unnest(val) val array_test\     ) data_points using (idx); 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -