Reputation: 1391
$array = array
(
53 => array('num' => 20,'name' => 'aaa'),
10 => array('num' => 20,'name' => 'bbb')
);
$sql ="INSENT INTO data(id,num,name) VALUES('53','20','aaa'),('10','20','bbb')
";
How to convert $array to ('53','20','aaa'),('10','20','bbb')
?
Thanks
Upvotes: 4
Views: 9935
Reputation: 16973
implode() can help you do this, though you will need to loop through and apply it to each individual array:
$resultStrings = array();
foreach ($array as $key => $values) {
$subarrayString = "('$key','" . implode($values, "','") . "')";
$resultStrings[] = $subarrayString;
}
$result = implode($resultStrings, ",");
Upvotes: 6
Reputation: 6153
loop through them using foreach:
$result = '';
foreach ($array as $key=>$subarray) {
$result .= "('$key'";
foreach ($subarray as $el) {
$result .= ",'$el'";
}
$result .= "),";
}
//get rid of the trailing comma
$result = substr($result,0,-1);
et voilá
Upvotes: 0
Reputation: 164760
I'd do this using a prepared statement and a simple loop, eg
$db = new PDO(...);
$stmt = $db->prepare('INSERT INTO data(id, num, name) VALUES (?, ?, ?)');
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $num);
$stmt->bindParam(3, $name);
foreach ($array as $id => $vals) {
$num = $vals['num'];
$name = $vals['name'];
$stmt->execute();
}
Upvotes: 1