获取JSON数据

时间:2017-08-04 07:30:11

标签: php json postgresql

我在使用PHP获取JSON数据时遇到了问题。下面是我的代码和JSON文件。问题是它只获取JSON的第一个产品,并且不会遍历整个循环。

我知道必须有一点错误,因为它只取得第一行。

<html>  
      <head>  
           <title>Test</title> 
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
           <style>

            .box
            {
                width:750px;
                padding:20px;
                background-color:#fff;
                border:1px solid #ccc;
                border-radius:5px;
                margin-top:100px;
            }
        </style>
      </head>  
      <body>  
            <div class="container box">
                <h3 align="center">Import JSON File Data into Postgresql</h3><br />
                <?php
                $host = "localhost"; // db ip
                $user = "postgres"; // db username (mention your db password here)
                $pass = "postgres";// database password
                $db = "json_order"; // db 
                    // Connecting to my database 
                $connect = pg_connect("host=$host dbname=$db user=$user password=$pass") or die ("Could not connect to server\n");
                //$connect = mysqli_connect("localhost", "root", "", "employee"); //Connect PHP to MySQL Database
                $query = '';
                $table_data = '';
                $filename = "testdata.json";
                $data = file_get_contents($filename); //Read the JSON file in PHP
                $array = json_decode($data, true); //Convert JSON String into PHP Array
                $i=0;
                foreach($array as $row) //Extract the Array Values by using Foreach Loop
                {
                            // Make Multiple Insert Query 
                    $query .= "INSERT INTO order_insert(id,title) VALUES ('".$row[$i]["id"]."', '".$row[$i]["title"]."')";      // Make Multiple Insert Query 

                    $table_data .= '
                        <tr>
                            <td>'.$row[$i]["id"].'</td>
                            <td>'.$row[$i]["title"].'</td>
                        </tr>
                    ';                  
                    $i++;
                }
                if(pg_query($connect, $query))  //Run Mutliple Insert Query
                {
                    echo '<h3>Imported JSON Data</h3><br />';

                    echo '
                        <table class="table table-bordered">
                                <tr>
                                    <th width="45%">ID</th>
                                    <th width="10%">Title</th>
                                </tr>
                    ';
                    echo $table_data;       
                    echo '</table>';
                }




                ?>
                <br />
            </div>  
      </body>  
</html> 

/////////////////// Json File(testdata.json)/////////////////

{  
   "products":[  
      {  
         "id":4790584326,
         "title":"Black Sand"
      },
      {  
         "id":4790581318,
         "title":"Black Sea"
      },
      {  
         "id":4790599046,
         "title":"BLOSSOM MANAMI (02-A)"
      },
      {  
         "id":4790598534,
         "title":"BLOSSOM MANAMI (02-B)"
      },
      {  
         "id":4790587462,
         "title":"Blue Breeze"
      },
      {  
         "id":4790600326,
         "title":"Bow Bells"
      },
      {  
         "id":1008999299,
         "title":"Copy of Product 1"
      },
      {  
         "id":4790601542,
         "title":"Coral Charm"
      },
      {  
         "id":4790588550,
         "title":"Coral spectrum"
      },
      {  
         "id":4790589446,
         "title":"Dazzling Sea"
      },
      {  
         "id":4790600646,
         "title":"Emerald Woo"
      },
      {  
         "id":4790592518,
         "title":"Enchanted Blossom"
      },
      {  
         "id":4790595206,
         "title":"FLORAL SAGA (05-A)"
      },
      {  
         "id":4790595846,
         "title":"FLORAL SAGA (05-B)"
      },
      {  
         "id":4790596678,
         "title":"FLORENTINA (08-A)"
      },
      {  
         "id":4790596422,
         "title":"FLORENTINA (08-B)"
      },
      {  
         "id":4790593030,
         "title":"IMPERIAL BOUQUET (06-A)"
      },
      {  
         "id":4790594630,
         "title":"IMPERIAL BOUQUET (06-B)"
      },
      {  
         "id":4790598150,
         "title":"IRIS INVERSE (03-A)"
      },
      {  
         "id":4790597958,
         "title":"IRIS INVERSE (03-B)"
      },
      {  
         "id":4790585606,
         "title":"Mesmerised Ocean"
      },
      {  
         "id":6517629254,
         "title":"Mesmerising Bouquet"
      },
      {  
         "id":4790591046,
         "title":"Midnight Grandeur"
      },
      {  
         "id":4790599750,
         "title":"MORNING FLOSS (01-A)"
      },
      {  
         "id":4790599366,
         "title":"MORNING FLOSS (01-B)"
      },
      {  
         "id":4790584774,
         "title":"Mother of pearls"
      },
      {  
         "id":4790590662,
         "title":"Nautical Overboard"
      },
      {  
         "id":4790583558,
         "title":"Ocean Punch"
      },
      {  
         "id":4790584006,
         "title":"Opal Muse"
      },
      {  
         "id":9229155654,
         "title":"p1"
      },
      {  
         "id":9256445510,
         "title":"p1"
      },
      {  
         "id":1005959875,
         "title":"Product 1"
      },
      {  
         "id":4790592006,
         "title":"Radiant Rose"
      },
      {  
         "id":4790582278,
         "title":"Rogue Breeze"
      },
      {  
         "id":4790597702,
         "title":"ROSABELLA (04-A)"
      },
      {  
         "id":4790597062,
         "title":"ROSABELLA (04-B)"
      },
      {  
         "id":4790581830,
         "title":"Sea News"
      },
      {  
         "id":4790586438,
         "title":"Seaweed lust"
      },
      {  
         "id":4790600966,
         "title":"Spiritual Marvel"
      },
      {  
         "id":8994515974,
         "title":"Stitch My Fabric"
      },
      {  
         "id":1949467075,
         "title":"test4"
      },
      {  
         "id":1949486851,
         "title":"test4"
      },
      {  
         "id":4790582854,
         "title":"Ultramarine"
      },
      {  
         "id":4790591558,
         "title":"Viva Glam"
      },
      {  
         "id":4790594118,
         "title":"WHIMSICAL VINES (07-A)"
      },
      {  
         "id":4790593478,
         "title":"WHIMSICAL VINES (07-B)"
      }
   ]
}

5 个答案:

答案 0 :(得分:1)

由于您使用foreach($array as $row)来循环JSON数据,因此无需使用$i变量,因为json对象的eache元素可通过$row变量访问

编辑:

此外,多插入查询应采用以下格式:

INSERT INTO table(column1, column2) VALUES (value1, value2), ( Value1, Value2 )....

所以将代码更改为:

$query = "INSERT INTO order_insert(id,title) VALUES ";
foreach($array['products'] as $row) //Extract the Array Values by using Foreach Loop
            {
                        // Make Multiple Insert Query 
                $query .= " ('".$row["id"]."', '".$row["title"]."'), ";      // Make Multiple Insert Query 

                $table_data .= '
                    <tr>
                        <td>'.$row["id"].'</td>
                        <td>'.$row["title"].'</td>
                    </tr>
                ';                  
            }

第二次编辑:

最终查询最后会有一个,,所以要删除你应该这样做:

$theQuery = rtrim($theQuery,", ");

这是一个有效的Fiddle

答案 1 :(得分:1)

你可以尝试一下。

<html>  
      <head>  
           <title>Test</title> 
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
           <style>

            .box
            {
                width:750px;
                padding:20px;
                background-color:#fff;
                border:1px solid #ccc;
                border-radius:5px;
                margin-top:100px;
            }
        </style>
      </head>  
      <body>  
            <div class="container box">
                <h3 align="center">Import JSON File Data into Postgresql</h3><br />
                <?php
                $host = "localhost"; // db ip
                $user = "postgres"; // db username (mention your db password here)
                $pass = "postgres";// database password
                $db = "json_order"; // db 
                    // Connecting to my database 
                $connect = pg_connect("host=$host dbname=$db user=$user password=$pass") or die ("Could not connect to server\n");
                //$connect = mysqli_connect("localhost", "root", "", "employee"); //Connect PHP to MySQL Database
                $query = '';
                $table_data = '';
                $filename = "testdata.json";
                $data = file_get_contents($filename); //Read the JSON file in PHP
                $array = json_decode($data, true); //Convert JSON String into PHP Array
                $i=0;
                foreach($array['products'] as $row) //Extract the Array Values by using Foreach Loop
                {
                            // Make Multiple Insert Query 
                    $query .= "INSERT INTO order_insert(id,title) VALUES ('".$row["id"]."', '".$row["title"]."')";      // Make Multiple Insert Query 

                    $table_data .= '
                        <tr>
                            <td>'.$row["id"].'</td>
                            <td>'.$row["title"].'</td>
                        </tr>
                    ';                  
                    $i++;
                }
                if(pg_query($connect, $query))  //Run Mutliple Insert Query
                {
                    echo '<h3>Imported JSON Data</h3><br />';

                    echo '
                        <table class="table table-bordered">
                                <tr>
                                    <th width="45%">ID</th>
                                    <th width="10%">Title</th>
                                </tr>
                    ';
                    echo $table_data;       
                    echo '</table>';
                }




                ?>
                <br />
            </div>  
      </body>  
</html> 

答案 2 :(得分:0)

使用此

foreach($array->products as $row) //Extract the Array Values by using Foreach Loop
                {
                            // Make Multiple Insert Query 
                    $query .= "INSERT INTO order_insert(id,title) VALUES ('".$row[$i]["id"]."', '".$row[$i]["title"]."')";      // Make Multiple Insert Query 

                    $table_data .= '
                        <tr>
                            <td>'.$row->id.'</td>
                            <td>'.$row->title.'</td>
                        </tr>
                    ';                  

                }

答案 3 :(得分:0)

你需要遍历产品数组

            $i=0; //remove no need
            foreach($array['products'] as $row)  //change to $array['products']
            {
                        // Make Multiple Insert Query 
                $query .= "INSERT INTO order_insert(id,title) VALUES ('".$row["id"]."', '".$row["title"]."')";      // Make Multiple Insert Query 

                $table_data .= '
                    <tr>
                        <td>'.$row["id"].'</td>
                        <td>'.$row["title"].'</td>
                    </tr>
                ';                  
                $i++;
            }

答案 4 :(得分:0)

错误在于您正在访问对象,而不是数组 所以它只需将其作为$row->id$row->title访问它 并且该对象是嵌套的(对象的对象) 因此双foreach循环 这是一个没有数据库部分的显示工作code 这是一个基于您的代码的工作代码,我只是更改了值演示文稿:

 $data='{  
       "products":[  
          {  
             "id":4790597958,
             "title":"IRIS INVERSE (03-B)"
          },
          {  
             "id":4790585606,
             "title":"Mesmerised Ocean"
          },
          {  
             "id":6517629254,
             "title":"Mesmerising Bouquet"
          }
       ]
    }';
    echo "<pre>";
    $array = json_decode($data); //Convert JSON String into PHP Array

    foreach($array as $value) //Extract the Array Values by using Foreach Loop
    {
        foreach($value as $row){
        $query .= "INSERT INTO order_insert(id,title) VALUES ('".$row->id."', '".$row->title."'), ";      // Make Multiple Insert Query 

                $table_data .= '
                    <tr>
                        <td>'.$row->id.'</td>
                        <td>'.$row->title.'</td>
                    </tr>
                ';       
        }
    }
祝你好运,