如何将多维数组的嵌套数组插入MySQL

时间:2018-07-03 08:10:24

标签: php mysql arrays json multidimensional-array

我有一个多维愿望,我想插入到mysql数据库中。一切正常,但由于行会在嵌套数组之后重复出现,因此这是一个更好的解决方案

这是我的json

{
    "results": [
        {
            "id": 48728,
            "name": "MOVIES AT THE PARK @ GIBA GORGE",
            "url": "Some URL",
            "imageUrl": "Some Path",
            "dateCreated": "2018-06-08T09:18:59.717",
            "lastModified": "2018-06-26T14:20:45.0214921",
            "startDate": "2018-07-28T17:00:00",
            "endDate": "2018-07-28T22:00:00",
            "venue": {
                "id": 0,
                "name": "Giba Gorge Mountain Bike Park",
                "addressLine1": "110 Stockville Road",
                "addressLine2": "",
                "latitude": -29.8276051,
                "longitude": 30.781735700000013
            },
            "locality": {
                "levelOne": "South Africa",
                "levelTwo": "KwaZulu-Natal",
                "levelThree": "Clifton Canyon"
            },
            "organiser": {
                "id": 0,
                "name": "Ultra Glow SA ",
                "phone": "0822603351",
                "mobile": "0828927837",
                "facebookUrl": "",
                "twitterHandle": "",
                "hashTag": "UGMOVIES",
                "organiserPageUrl": "some url"
            },
            "categories": [
                {
                    "id": 3,
                    "name": "Film & Media"
                },
                {
                    "id": 12,
                    "name": "Food & Drink"
                }
            ],
            "tickets": [
                {
                    "id": 98655,
                    "name": "ADULT TICKET",
                    "soldOut": false,
                    "provisionallySoldOut": false,
                    "price": 100,
                    "salesStart": "2018-06-26T11:52:00",
                    "salesEnd": "2018-07-28T17:00:00",
                    "description": "",
                    "donation": false,
                    "vendorTicket": false
                },
                {
                    "id": 98656,
                    "name": "UNDER 12",
                    "soldOut": false,
                    "provisionallySoldOut": false,
                    "price": 80,
                    "salesStart": "2018-06-26T11:53:00",
                    "salesEnd": "2018-07-28T17:00:00",
                    "description": "",
                    "donation": false,
                    "vendorTicket": false
                }
            ],
            "schedules": [
            ],
            "refundFeePayableBy": 0
        },
        {
            "id": 51681,
            "name": "ULTRA GLOW COLOUR CRUZ @ RIETVLEI ZOO FARM",
            "url": "some url",
            "imageUrl": "some path",
            "dateCreated": "2018-06-26T12:12:07.3",
            "lastModified": "2018-06-28T15:22:24.1579751",
            "startDate": "2018-08-12T10:00:00",
            "endDate": "2018-08-12T14:00:00",
            "venue": {
                "id": 0,
                "name": "Rietvlei Zoo Farm",
                "addressLine1": "101 Swartkoppies Road",
                "addressLine2": "",
                "latitude": -26.3117147,
                "longitude": 28.07989120000002
            },
            "locality": {
                "levelOne": "South Africa",
                "levelTwo": "Gauteng",
                "levelThree": "Johannesburg South"
            },
            "organiser": {
                "id": 0,
                "name": " Ultra Glow South Africa",
                "phone": "0822603351",
                "mobile": "0828927837",
                "facebookUrl": "",
                "twitterHandle": "",
                "hashTag": "",
                "organiserPageUrl": "some url"
            },
            "categories": [
                {
                    "id": 60,
                    "name": "Trail Running"
                },
                {
                    "id": 5,
                    "name": "Sports & Fitness"
                }
            ],
            "tickets": [
                {
                    "id": 98735,
                    "name": "ADULT EARLY BIRD",
                    "soldOut": false,
                    "provisionallySoldOut": false,
                    "price": 150,
                    "salesStart": "2018-06-26T12:47:00",
                    "salesEnd": "2018-08-12T10:00:00",
                    "description": "",
                    "donation": false,
                    "vendorTicket": false
                },
                {
                    "id": 98736,
                    "name": "UNDER 12 - EARLY BIRD",
                    "soldOut": false,
                    "provisionallySoldOut": false,
                    "price": 120,
                    "salesStart": "2018-06-26T12:47:00",
                    "salesEnd": "2018-08-12T10:00:00",
                    "description": "",
                    "donation": false,
                    "vendorTicket": false
                }
            ],
            "schedules": [
            ],
            "refundFeePayableBy": 0
        }
    ],
    "pageSize": 10,
    "pages": 1,
    "records": 2,
    "extras": null,
    "message": null,
    "statusCode": 0
}

我尝试了以下代码将相关数据插入数据库

<?php
$connect= mysqli_connect("localhost","root","","result");
$jsondata=file_get_contents("result.json");
$json= json_decode($jsondata,true);
$results=$json['results'];
$n= sizeof($results);
for($i=0;$i<$n;$i++){

$row=$results[$i];
foreach($row['tickets'] as $key => $value){


 $sql="INSERT into 
 event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketNa me,price) 
 VALUES('".$row["name"]."','".$row["url"]."','".$row["imageUrl"]."','".$row["dateCreated"]."','".$row["venue"]["name"]."','".$row["venue"]["addressLine1"]."','".$row["venue"]["addressLine2"]."','".$value["name"]."','".$value["price"]."')";

    mysqli_query($connect,$sql);
    }
}

echo "events data inserted";
?>

这会将各自的数据输入到我的数据库中,但是由于嵌套数组tickets具有各自的键nameprice,相同的事件像{{1 }}的价格MOVIES AT THE PARK @ GIBA GORGE是一行,而100的价格MOVIES AT THE PARK @ GIBA GORGE是另一行...以后,我必须将这些数据作为一个事件名称的一部分与票证一起显示类型和价格作为表格...您对我可以做得更好的任何其他方式有什么想法,而不是对同一事件有两行?

预先感谢

对于那些一直建议我不要使用for和foreach循环的人来说,这是删除for循环和单个foreach循环后的更新代码,这给我一个错误的含义,即在票证下名称和价格的索引未定义

80

因此,我通过使用两个foreach循环进一步更新了我的代码,一个循环遍历顶级数组“结果”,另一个循环遍历嵌套数组“票证”

<?php
$connect= mysqli_connect("localhost","root","","result");
$jsondata=file_get_contents("result.json");
$json= json_decode($jsondata,true);
$results=$json['results'];

foreach($results as $key => $result){

    $sql="INSERT into `event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketName,price) VALUES('".$result["name"]."','".$result["url"]."','".$result["imageUrl"]."','".$result["dateCreated"]."','".$result["venue"]["name"]."','".$result["venue"]["addressLine1"]."','".$result["venue"]["addressLine2"]."','".$result["tickets"]["name"]."','".$result["tickets"]["price"]."')";`
    mysqli_query($connect,$sql);
}

echo "events data inserted";
?>

遍历嵌套数组,所以我的代码现在没有任何问题,唯一的问题是由于“票证”数组中有两种成人票和儿童票,我的桌子上有2个事件

因此,根据这里的许多建议,我需要为事件和票证创建两个单独的表,如果有人可以告诉我如何将这两个表连接起来以便能够以票证类型显示html中的事件信息,我将不胜感激和价格在html表格标签中显示

2 个答案:

答案 0 :(得分:0)

这是因为您在for中使用了foreach。您只需要一个foreach:

foreach ($multiArray as $key => $singleArray) {
    //rest of code, replacing $row with $singleArray['key']. E.g. $singleArray['id']
}

在看到OP更新后更新:

所以您会这样做:

foreach ($results as $row) {
  foreach ($row['tickets'] as $ticket) {
    //sql
  }
}

这应该允许您在SQL中使用$ticket['key']-尽管我确实建议切换到PDO准备好的语句以保护自己免受SQL注入。

还有其他建议,将票证分离到自己的表中将对您非常有利。

答案 1 :(得分:0)

正在发生的主要原因是看下面的代码:

$row=$results[$i];
foreach($row['tickets'] as $key => $value){

    $sql="INSERT into event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketNa me,price) VALUES('".$row["name"]."','".$row["url"]."','".$row["imageUrl"]."','".$row["dateCreated]."','".$row["venue"]["name"]."','".$row["venue"]["addressLine1"]."','".$row["venue"]["addressLine2"]."','".$value["name"]."','".$value["price"]."')";

    mysqli_query($connect,$sql);
}

$row包含您的一个主要条目,而$row['tickets']包含2个条目,并且您正在使用票证循环内的$ row主要内容。这就是为什么您获得2个条目的原因。解决此问题的最佳方法是使用单个foreach循环,而不是使用for和foreach。

编辑:

实际上,我建议将表归一化,将其分为2个表,一个表用于存储事件信息,另一个表用于使用票证信息。参见下面的结构:

event(id,name,url,imageUrl,addressLine1,addressLine2,dateCreated);
event_tickets(id,event_id,ticketName,price,dateCreated);

这将帮助您轻松维护信息。您也可以将代码修改为如下形式:

$sql="INSERT into event(name,url,imageUrl,addressLine1,addressLine,2dateCreated) VALUES ('".$row['name']."','".$row['url']."','".$row['imageUrl']."','".$row['venue']['addressLine1']."','".$row['venue']['addressLine2']."','".date('Y-m-d h:i:s')."');"
mysqli_query($connect, $sql);
$event_id = mysqli_insert_id($connect);

然后您可以使用foreach将票证信息插入到event_tickets表中。

希望这会有所帮助