dounai9592 2018-08-07 18:08 采纳率: 100%
浏览 66

JSON - > PHP中的多维数组 - > SQL

I am struggling with the problem of transferring json-multidimensional array data to SQL.

This is my json file (data.json):

{
    "Data 1": {
        "Text1": "Anything1",
        "Text2": "Anything2"
    },
    "Data 2": {
        "2018-08-02": {
            "1.": "145",
            "2.": "258"
        },
        "2018-08-03": {
            "1.": "428",
            "2.": "528"
        },
        "2018-08-04": {
            "1.": "727",
            "2.": "514"
        }
    }
}

I have a php code:

<?php
$db = new PDO('mysql:host=localhost;dbname=test','root','');
$jsonData = file_get_contents('data.json');
$data = json_decode($jsonData, true);
?>

So now I have a php array $data.

I need to load an array into the following columns in sql: "DATE" (eg "2018-08-02" etc), "1.", "2.". This is what the final effect in mysql should look like

And I do not know what to do next.

I tried to do as it is shown in this video: https://www.youtube.com/watch?v=4zTjCpBqSbw and ia other websites (https://www.w3schools.com/js/js_json_php.asp), but for me the date (eg "2018-08-02") is a variable and I do not know how to solve the problem in this case.

  • 写回答

1条回答 默认 最新

  • douchuituo3032 2018-08-07 20:57
    关注

    Here's one way you could do it.

    https://3v4l.org/peLqP

    BUT you should not be inserting data in this way - this is for illustration only. Use prepared statements or something similar.

        <?php
        $json = "{
        \"Data 1\": {
            \"Text1\": \"Anything1\",
            \"Text2\": \"Anything2\"
        },
        \"Data 2\": {
            \"2018-08-02\": {
                \"1.\": \"145\",
                \"2.\": \"258\"
            },
            \"2018-08-03\": {
                \"1.\": \"428\",
                \"2.\": \"528\"
            },
            \"2018-08-04\": {
                \"1.\": \"727\",
                \"2.\": \"514\"
            }
        }
    }";
    
    $jsonDecoded = json_decode($json, true);
    foreach ($jsonDecoded['Data 2'] as $dateKey => $data) {
        $values = implode(',', $data);
        $statement = "INSERT INTO mytable (TheDate, Value1, Value2) VALUES ('{$dateKey}'," . $values . ");";
        echo $statement . PHP_EOL;
    }
    

    Output:

    INSERT INTO mytable (TheDate, Value1, Value2) VALUES ('2018-08-02',145,258);
    INSERT INTO mytable (TheDate, Value1, Value2) VALUES ('2018-08-03',428,528);
    INSERT INTO mytable (TheDate, Value1, Value2) VALUES ('2018-08-04',727,514);
    
    评论

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥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如何实现在堆积颗粒的上表面加载高斯热源