Reputation: 3131
I'm trying to do a bulk insert to MySQL so I need to end up with the values in this format:
(1,2,2),(1,2,8),(1,2,0)
Currently I can generate a multidimensional array:
Array
(
[0] => Array
(
[key1] => 1
[key2] => 2
[key3] => 2
)
[1] => Array
(
[key1] => 1
[key2] => 2
[key3] => 8
)
[2] => Array
(
[key1] => 1
[key2] => 2
[key3] => 0
)
)
What is the most efficient method to convert the array to the 'grouped comma seperated list' that I need?
Upvotes: 0
Views: 66
Reputation: 26375
Probably something like this, presuming you don't need to worry about escaping commas and parentheses in your data.
foreach ($arrays as &$array) {
$array = '('.implode(',', $array).')';
}
$csv = implode(',', $arrays);
Upvotes: 2
Reputation: 9356
Try concatenating the array into a string for the insert.
foreach($array as $a){
$output .= '('.$a['key1'].','.$a['key2'].','.$a['key3'].'),';
}
$output = substr($output, 0, -1); // remove the last comma
Upvotes: 1
Reputation: 281
Why not to use php's implode
function?
In this case I'd do two loops:
$gather=array(); //here we will keep all single arrays
$multi=array(array('1','2','3'),array('4','5','6'));
foreach($multi as $single)
{
$gather[]="(".implode($single,',').")";
}
print_r(implode(",",$gather)); //(1,2,3),(4,5,6)
Upvotes: 0