如何使用PHP和Mysql

时间:2016-10-17 06:32:54

标签: php mysql arrays

我需要一个帮助。我需要使用PHP和MySQL将一些Json对象值的多个数据插入到表中。我在下面解释我的代码。

$commnt=[{
   'day_id':2,
   'comment':'vodka1'
},{
  'day_id':3,
  'comment':'vodka2'
}
]

$result=[{
    'day_id':1,
    'restaurant':'193'
},{
  'day_id':2,
  'restaurant':'193'
},{
  'day_id':3,
  'restaurant':'193'
}
]

这里我需要按照day_id将Json对象中的所有数据输入到下表中。我正在解释下表中的栏目。

  

db_details:

id   day_id   restaurant  comment

此处我的要求是,当day_id相同时,相应的comment字段值将进入表格,其他明智的comment字段值将保持为空白。预期的输出值如下所示。

id    day_id   restaurant   comment

1       1        193               

2       2        193         vodka1

3       3        193         vodka3

我的查询如下。

$insertintodetails=mysqli_query($connect,'INSERT INTO db_details
(day_id,restaurant,comment) values ("'. $result.'","'.$result[$i]['restaurant'].'","'.$commnt[$i]['comment'].'")');

这里可能有很多用例,例如Json对象长度可能相同或不同,但注释应按day_id插入,否则将保持空白。在我的查询中,我无法按要求插入。请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

$newArray = $insertintodetails = array();
foreach($result as $rs)
{
  $newArray[$rs->day_id] = [
    "`day_id`=>'{$rs->day_id}'",
    "`restaurant`=>'{$rs->restaurant}'"
];
}
foreach($commnt as $rs){
  $newArray[$rs->day_id][] = "`comment`='{$rs->comment}'";
}
foreach($newArray as $rs){
  $insertintodetails[]=mysqli_query($connect,'INSERT INTO db_details SET '.implode(',',$rs));
}

答案 1 :(得分:-1)

我在您的问题详细信息上方创建了一个示例。你可以尝试下面的代码。它应该对你有用......

//For example taken array and convert it to JSON    
$comment = json_encode(array(array('day_id' => '2', 'comment' => 'vodka1'), array('day_id' => '3', 'comment' => 'vodka2')));
$result = json_encode(array(array('day_id' => '1', 'restaurant' => '193'), array('day_id' => '2', 'restaurant' => '193'), array('day_id' => '3', 'restaurant' => '193')));

//Convert JSON to array...
$arrComment = json_decode($comment, true);
$arrResult = json_decode($result, true);

foreach($arrResult AS $keyResult => $dataResult){
    $day_id = $dataResult['day_id'];//day_id
    $restaurant = $dataResult['restaurant'];//rasturant
    $strComment = '';//comment
    //Check and extract comment value from multi dimensional comment($arrComment) array...
    if($getComment = find_comment_with_dayid($arrComment, $day_id)){
      $strComment = $getComment;
    }

    //Insert records...
    $insertintodetails=mysqli_query($connect,'INSERT INTO db_details
(day_id, restaurant, comment) values ("'. $day_id .'","'. $restaurant .'","'. $strComment .'")');
}


//Function will return comment for matched day_id
function find_comment_with_dayid($arrComment, $fieldKey) {
    foreach($arrComment as $indCommenr => $dataComment) {
        //Check for day_id, matched then return comment...
        if($dataComment['day_id'] == $fieldKey) return $dataComment['comment'];
    }
    return FALSE;
}

在这里,我采用了示例数组来避免在您的问题上报告JSON问题。希望这项工作做得好!