如何调用处理另一个数组的foreach循环内部的外部数组

时间:2016-07-03 18:24:11

标签: php arrays foreach

我有一个外部数据,可以包含数据(站点和时间)。 我想比较我的数据库中是否已存在该数据,如果它不存在则插入该特定站或者如果时间不等于数据库中的时间更新它。我只是不知道如何在我循环数据库数据的foreach循环中调用外部数据,所以我现在将插入和更新部分放在一边。

这是我的代码:

private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {                                             
   try{
        String selected=(String)jComboBoxSelected.getSelectedItem();
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
        + "employee_certificate","root","");

          String sql="SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
            + "certificate.Cert_Code, certificate.Cert_Name,\n" +
            "certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
            + "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
              + " ON stuff.Emp_Id=certificate.Emp_Id  "
                + "WHERE "+selected+" =? ORDER BY stuff.Emp_Name\n" ;

  PreparedStatement  pstmt=con.prepareStatement(sql);
   pstmt.setString(1, jTextFieldSearch.getText());
     ResultSet rs=pstmt.executeQuery();
       jTable1.setModel(DbUtils.resultSetToTableModel(rs));
        pstmt.close();
           //con.close();
    }
    catch(Exception ex){ex.printStackTrace();} 
}                                            

print $ data_array:

<?php
// all database parameters
require_once("config.php");

// main array usually contains up to around 40 arrays
$data_array = array(
                array("time"=>"2016-07-01 19:00:00", "name_station"=>"RC Bilogora", "type_station"=>"1", "longitude"=>"17.162", "latitude"=>"45.882", "temperature"=>"28.8"),
                array("time"=>"2016-07-01 19:00:00", "name_station"=>"Bjelovar", "type_station"=>"1", "longitude"=>"16.869", "latitude"=>"45.910", "temperature"=>"28.6"),
                array("time"=>"2016-07-01 19:00:00", "name_station"=>"Crikvenica", "type_station"=>"1",  "longitude"=>"14.689", "latitude"=>"45.173", "temperature"=>"28.0")
                );

// print $data_array
echo "Data from external array";
echo "<pre>";
print_r($data_array);
echo "</pre>";
echo "<hr>";

try {
        // connect to the database
        $dbh = new PDO('pgsql:host='.DB_HOST. ';port=' .DB_PORT. ';dbname=' .DB_NAME, DB_USER, DB_PASS);

        // start transaction
        $dbh->beginTransaction();

        // query
        $sql_select = "SELECT station, time FROM vwstationmeasurmentdva";
        $stmt_select = $dbh->prepare($sql_select);
        $stmt_select->execute();
        $result_select = $stmt_select->fetchAll(PDO::FETCH_ASSOC);

        // print results from sql for view stationmeasurment
        echo "Station and time from database captured with FETCH ASSOC";
        echo "<pre>";
        print_r($result_select);
        echo "</pre>";
        echo "<hr>";

        $number_of_rows = count($result_select);

        // FOREACH loop
        $result_vwstationmeasurment_select_array = array ();
        foreach($result_select as $row) {
            $station_name_db = $row['station'];
            $time_db = $row['time'];
            echo $station_name_db . "<br>";
            echo $time_name_db . "<br>";

            // PROBLEM: I DONT KNOW HOW TO CALL $station_name AND $time BEFORE THIS IF STATEMENT SO I CAN DO THE IF STATEMENT
            if ($station_name_db != $station_name OR empty($station_name_db)){
               echo "This station is not in a database or there are no data for stations in a database at all so insert that station";
            } elseif ($time_db != $time){
               echo "Time from external data is not equal to the time in a database so update time in a database";
            }

            $result_vwstationmeasurment_select_array[] =($row);
    };


        // save transaction
        $dbh->commit();

        // close database connection
        $dbh = null;

} catch (PDOException $e) {
        // cancel the transaciton if something went wrong and write msg about it
        $dbh->rollBack();
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
}
?>

print $ result_select:

使用FETCH ASSOC捕获的数据库的站点和时间

Data from external array
Array
(
    [0] => Array
        (
            [time] => 2016-07-01 19:00:00
            [name_station] => RC Bilogora
            [type_station] => 1
            [longitude] => 17.162
            [latitude] => 45.882
            [temperature] => 28.8
        )

    [1] => Array
        (
            [time] => 2016-07-01 19:00:00
            [name_station] => Bjelovar
            [type_station] => 1
            [longitude] => 16.869
            [latitude] => 45.910
            [temperature] => 28.6
        )

    [2] => Array
        (
            [time] => 2016-07-01 19:00:00
            [name_station] => Crikvenica
            [type_station] => 1
            [longitude] => 14.689
            [latitude] => 45.173
            [temperature] => 28.0
        )

)

FOREACH LOOP:

Array
(
    [0] => Array
        (
            [station] => RC Bilogora
            [time] => 2016-07-01 16:00:00
        )

    [1] => Array
        (
            [station] => Bjelovar
            [time] => 2016-07-01 16:00:00
        )

    [2] => Array
        (
            [station] => Dubrovnik
            [time] => 2016-07-01 16:00:00
        )

    [3] => Array
        (
            [station] => Gospić
            [time] => 2016-07-01 16:00:00
        )

    [4] => Array
        (
            [station] => RC Gorice (kod Nove Gradiške)
            [time] => 2016-07-01 16:00:00
        )

    [5] => Array
        (
            [station] => RC Gradište (kod Županje)
            [time] => 2016-07-01 16:00:00
        )

    [6] => Array
        (
            [station] => Hvar
            [time] => 2016-07-01 16:00:00
        )

    [7] => Array
        (
            [station] => Karlovac
            [time] => 2016-07-01 16:00:00
        )
...

已编辑(@PaulH)

我的方式根本不起作用......你可以通过代码向我推荐一些东西......

RC Bilogora
2016-07-01 16:00:00
Bjelovar
2016-07-01 16:00:00
Dubrovnik
2016-07-01 16:00:00
Gospić
2016-07-01 16:00:00
RC Gorice (kod Nove Gradiške)
2016-07-01 16:00:00
RC Gradište (kod Županje)
2016-07-01 16:00:00
Hvar
2016-07-01 16:00:00
Karlovac
2016-07-01 16:00:00...

打印:

try {
        // connect to the database
        $dbh = new PDO('pgsql:host='.DB_HOST. ';port=' .DB_PORT. ';dbname=' .DB_NAME, DB_USER, DB_PASS);

        // start transaction
        $dbh->beginTransaction();

        // EDITED
        foreach($data_array as $row){
                $station_external = $row['name_station'];
                $time_external = $row['time'];
                echo $station_external . "<br>";
                echo $time_external . "<br>";


                // query
                $sql_select = "SELECT station, time FROM vwstationmeasurmentdva";
                $stmt_select = $dbh->prepare($sql_select);
                $stmt_select->execute();
                $result_select = $stmt_select->fetchAll(PDO::FETCH_ASSOC);

                // print results from sql for view stationmeasurment
                echo "Station and time from database captured with FETCH ASSOC";
                //echo "<h2>Ovo su stanica i vrijeme dohvaceni iz baze podataka samo uz pomoc print_r nakon FETCH ASSOC</h2>";
                echo "<pre>";
                print_r($result_select);
                echo "</pre>";
        } // THE END OF EDIT

                // save transaction
                $dbh->commit();

                // close database connection
                $dbh = null;

} catch (PDOException $e) {
                // cancel the transaciton if something went wrong and write msg about it
                $dbh->rollBack();
                print "Error!: " . $e->getMessage() . "<br/>";
                die();
}

1 个答案:

答案 0 :(得分:0)

答案是基于PaulH对我表示感谢的评论。教导某人的好方法,谢谢你给出的指示。

    foreach($data_array as $row){
            // station name from array
            $station_name = $row['name_station'];

            // query
            $sql_select = "SELECT station FROM vwstationmeasurmentdva WHERE station='$station_name'";
            $stmt_select = $dbh->prepare($sql_select);
            $stmt_select->execute();
            $result_select = $stmt_select->fetchAll(PDO::FETCH_ASSOC);

            $number_of_rows = count($result_select);
            if ($number_of_rows < 1){
                    echo " <br> Station doesn't exist in a database, we have to insert it. <br>";
            } else {
                    echo " <br> Station does exist in a database, so we will update the measurments. <br>";
           }
    }