0

If I have this array:

array(1) {
  ["ID"]=>
  string(1) "3"
}
array(1) {
  ["ID"]=>
  string(1) "6"
}
array(1) {
  ["ID"]=>
  string(1) "9"
}

And I want to have an output of this: 3, 6, 9

How can I concatenate or implode those array values to put in a variable so that I will use that variable with a value of like this: 3, 6, 9 in this: $this->db->set('SecondaryRoleID', $imploded);

user987654321
  • 119
  • 1
  • 1
  • 9

1 Answers1

4

Use the function array_column to extract the ID from each element into a single-dimensional array, then implode as usual:

echo implode(',', array_column($array, 'ID'));

If you are running PHP earlier than 5.5 then array_column is not available out of the box, so you have to provide equivalent code such as

echo implode(',', array_map(function($r) { return $r['ID']; }, $array));

That said, your proposed usage of the final result (sticking a comma-separated integer list representing item ids into a database field) is unusual and possibly wrong. For many-to-many relationships (each user can have many roles, and each role can be assigned to many users) the standard implementation is to use a join table, keeping your database schema normalized.

Jon
  • 428,835
  • 81
  • 738
  • 806