简体   繁体   中英

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 $assignee becomes a string instead of array. Output:

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

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';
}

Example/Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM