如何格式化 php 数组值并将它们插入数据库

Howto format php array values & insert them into database

这是我读取 csv 文件(从银行获取)、将其解析为数组并将其插入数据库的代码:

$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();

这是我的数组的样子:

[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"
 }

* * * * * * * 等等 * * * * * *

所以我的问题是:

1) 如何将 ["sifra"]=> "203 CZK" 转换为 ["sifra"]=> "203"(我只想在插入前显示数值)?

2) 如何将 ["Kupovni2"]=> "0,2821" 转换为 ["Kupovni2"]=> "0,282100"(我想要插入前 6 位小数)?

谢谢。

  1. 要从字符串中获取数字,您可以这样做

    $string = '203 CZK';
    echo (int) $string;
    

$string = '203 CZK';
echo filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
  1. 要使字符串长度为 8,您可以使用 str_pad

    $string = '0,2821';
    echo str_pad($string, 8, "0", STR_PAD_RIGHT);
    

结果:-

0,282100

另一种选择是使用 \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

Php demo

您的代码可能如下所示:

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();