patternsqlMinor
SQL Arrays are returned as strings in PHP
Viewed 0 times
returnedarrayssqlarephpstrings
Problem
I have a column with type
the result is
Any ideas?
Array, I need to get all the elements in the array, I tried:SELECT managers_ids::INTEGER[] FROM teams WHERE id = 14 the result is
'{8,9,10}'. How can I iterate on the results when it's returned as a string?Any ideas?
Solution
Using PHP with SQL Arrays
I would highly suggest never using PHP. However, when you can't avoid it you may find this post useful on reading PostgreSQL arrays as PHP Arrays. People have been complaining about this for 15 years now. PHP doesn't migrate SQL arrays into native PHP array structures.
Getting around the problem with JSON
The new method of working around PHP's long-standing inadequacies is to use
Attribution: shamefully stolen from michaelbn's answer on StackExchange..
Getting around the problem with
You have another option to use unnest and return a result set which PHP can handle.
I would highly suggest never using PHP. However, when you can't avoid it you may find this post useful on reading PostgreSQL arrays as PHP Arrays. People have been complaining about this for 15 years now. PHP doesn't migrate SQL arrays into native PHP array structures.
Getting around the problem with JSON
The new method of working around PHP's long-standing inadequacies is to use
JSON to move the array.SELECT array_to_json(pg_array_result) AS new_name FROM tbl1;
$array = json_decode($returned_field);Attribution: shamefully stolen from michaelbn's answer on StackExchange..
Getting around the problem with
unnestYou have another option to use unnest and return a result set which PHP can handle.
SELECT * FROM unnest(ARRAY[1,2,3]) AS t(x);
x
---
1
2
3
(3 rows)Code Snippets
SELECT array_to_json(pg_array_result) AS new_name FROM tbl1;
$array = json_decode($returned_field);SELECT * FROM unnest(ARRAY[1,2,3]) AS t(x);
x
---
1
2
3
(3 rows)Context
StackExchange Database Administrators Q#167242, answer score: 3
Revisions (0)
No revisions yet.