dongyi9023 2019-04-06 09:25 采纳率: 0%
浏览 59
已采纳

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

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>
  • 写回答

2条回答 默认 最新

  • doudu4282 2019-04-06 09:41
    关注

    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
    

    Php demo

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配