Last active
August 29, 2015 14:06
-
-
Save yitsushi/84cda81964f1dd32d664 to your computer and use it in GitHub Desktop.
ArrayMap example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function generateInsertSQL($table, $fields) { | |
$sql = "insert into `" . $table . "` "; | |
$sql .= "(" . implode( | |
", ", | |
array_map( | |
function($f) { return "`" . $f . "`"; }, | |
array_keys($fields[0]) | |
) | |
) . ") values\n"; | |
$sql .= " ". implode( | |
",\n ", | |
array_map( | |
function($field) { | |
return "(" . implode( | |
", ", | |
array_map( | |
function($v) { | |
if ($v === (int)$v) { return $v; } | |
if ($v === (float)$v) { return $v; } | |
return '"' . str_replace('"', "'", $v) . '"'; | |
}, | |
array_values($field) | |
) | |
) . ")"; | |
}, | |
$fields | |
) | |
) . "\n;"; | |
return $sql; | |
} | |
$users = array( | |
array( | |
'name' => "Amy Wang", | |
'age' => 29, | |
'weight' => 58.7 | |
), | |
array( | |
'name' => "Andy Roye", | |
'age' => 23, | |
'weight' => 64 | |
), | |
array( | |
'name' => "John's Son", | |
'age' => 53, | |
'weight' => 59.9 | |
), | |
array( | |
'name' => 'Peter "The Phoenix" Thomson', | |
'age' => 42, | |
'weight' => 114.2 | |
) | |
); | |
echo generateInsertSQL('users', $users), "\n"; |
Author
yitsushi
commented
Sep 10, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment