这是我的代码,我在其中读取csv文件(从银行获得),将其解析为数组并将其插入数据库:
select if( 'testString' in ( 0 ), 'TRUE', 'FALSE') from DUAL ;
这是我的数组的样子:
$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();
* * * * * * *等* * * * * *
所以我的问题是:
1)如何将[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"
}
转换为["sifra"]=> "203 CZK"
(我只希望在插入之前出现数字值)?
2)如何将["sifra"]=> "203"
转换为["Kupovni2"]=> "0,2821"
(我想在插入前保留小数点后6位)?
谢谢。
答案 0 :(得分:0)
要从字符串中获取数字,您可以采用这种方式
$name = !empty($seat[$first]['name']) ? $seat[$first]['name'] : $seat_no;
OR
$string = '203 CZK';
echo (int) $string;
要使字符串长度达到8,可以使用str_pad
$string = '203 CZK';
echo filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
结果:-
$string = '0,2821';
echo str_pad($string, 8, "0", STR_PAD_RIGHT);
答案 1 :(得分:0)
另一种选择是将\D+
的所有非数字替换为空字符串。
$digitsOnly = preg_replace('/\D+/', '', "203 CZK");
echo $digitsOnly; // 203
要附加零,可以使用str_pad:
$parts = explode(',', '0,2821');
$str = implode(',', [$parts[0], str_pad($parts[1], 6, '0', STR_PAD_RIGHT)]);
echo $str; // 0,282100
您的代码可能如下:
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();