如何格式化php数组值并将它们插入数据库[重复]
This question already has an answer here:
This is my code where I read csv file (which I get from the bank), parsing it into array & insert it into database:
$csvFile = file('tecajnica.csv');
$keys = str_getcsv(array_shift($csvFile), ';');
foreach ($csvFile as $csvRecord) {
// combine our $csvRecord with $keys array
$csv[] = array_combine($keys, str_getcsv($csvRecord, ';'));
}
foreach( $csv as $row) {
$db2 = new PDO ("odbc:as400");
$sqlf93p = $db2->prepare("INSERT INTO..... VALUES (".$row['sifra'].",".$row['Kupovni2']." ......)
$sqlf93p->execute();
This is how my array looks like:
[0]=>
array(10) {
["id"]=>
string(2) "67"
["drzava"]=>
string(10) "Australija"
["sifra"]=>
string(7) "036 AUD"
["VrijediZa"]=>
string(1) "1"
["Kupovni1"]=>
string(8) "4,5207"
["Kupovni2"]=>
string(8) "4,589597"
}
[1]=>
array(10) {
["id"]=>
string(0) ""
["drzava"]=>
string(5) "Ceska"
["sifra"]=>
string(7) "203 CZK"
["VrijediZa"]=>
string(1) "1"
["Kupovni1"]=>
string(8) "0,277098"
["Kupovni2"]=>
string(8) "0,2821"
}
* * * * * * * etc * * * * * *
So my questions are:
1) Howto convert ["sifra"]=> "203 CZK"
to ["sifra"]=> "203"
(I want only numeric value to appear before insert)?
2) Howto convert ["Kupovni2"]=> "0,2821"
to ["Kupovni2"]=> "0,282100"
(I want 6 decimal places before insert)?
Thanks.
</div>
Another option could be to replace all non digits using \D+
with an empty string.
$digitsOnly = preg_replace('/\D+/', '', "203 CZK");
echo $digitsOnly; // 203
For appending the zeroes, you might use str_pad:
$parts = explode(',', '0,2821');
$str = implode(',', [$parts[0], str_pad($parts[1], 6, '0', STR_PAD_RIGHT)]);
echo $str; // 0,282100
Your code might look like:
foreach( $csv as $row) {
$db2 = new PDO ("odbc:as400");
$sifra = preg_replace('/\D+/', '', $row['sifra']);
$parts = explode(',', $row['Kupovni2']);
$kupovni2 = implode(',', [$parts[0], str_pad($parts[1], 6, '0', STR_PAD_RIGHT)]);
$sqlf93p = $db2->prepare("INSERT INTO..... VALUES (". $sifra . "," . $kupovni2 ." ......);
$sqlf93p->execute();
-
To get number from a string you can do it this way
$string = '203 CZK'; echo (int) $string;
OR
$string = '203 CZK';
echo filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
-
To make string to length 8 you can use str_pad
$string = '0,2821'; echo str_pad($string, 8, "0", STR_PAD_RIGHT);
Result :-
0,282100