Alex G Alex G - 7 months ago 45
SQL Question

Create PHP array from MySQL's GROUP_CONCAT

I get data from MySQL query by using GROUP_CONCAT:

GROUP_CONCAT('id => ',assignments.userid,', assigned => ',assignments.assigned SEPARATOR ';') as assigneeids

And trying to convert it to PHP array.

$assignees = explode(';', $ticket['assigneeids']);
foreach($assignees as $assignee) {
echo "$assignee\n"; // $assignee['id'] outputs 'i'
echo gettype($assignee) . '\n';

But unfortunately
becomes a string instead of array. Output:

id => 1001, assigned => 1419648601
id => 1002, assigned => 1419649207

What am I doing wrong?


You're concatenating it into a string, not an array. Would you not be better off doing something like this?

GROUP_CONCAT(assignments.userid,'_',assignments.assigned SEPARATOR ';') as assigneeids

Once fetched, you'll need to do some explode()'ing magic

$assignees = explode(';', $ticket['assigneeids']);
foreach($assignees as $assignee) {
    list($id, $assigned) = explode("_", $assignee);
    echo "$id\n";
    echo gettype($assigned) . '\n';