如何将插入数组值存储为单独的记录

时间:2015-07-08 07:43:06

标签: php mysql arrays optimization

我在mySql表中有一个字段,即Expanse和另一个名为Amount的字段。 enter image description here

现在我想在';'的基础上打破扩展和数量字段中的字符串并将每个存储为单独的记录,以便其他字段中的数据,即id和name保持不变。这样enter image description here

我从orignal表中获取记录,并希望将此期望的结果存储在临时表中。从原始表中获取记录时,我在';'的基础上爆炸扩展和数量字符串。

 $query="SELECT * FROM table";
 $result=mysql_query($query);
 while ($row=mysql_fetch_array($result)) 
{
$newid=$row["id"];
$temp=explode(';',$row["expanse"]); 
$new=array_unique($temp);
//what to do after this ?


$temp2=explode(';',$row["amount"]); 
$new2=array_unique($temp2);
//what to do after this ? 
$query2="INSERT INTO table2 (id, $expanse,$amount)  VALUES   ('$newid','$new',$new2);
$result2=mysql_query($query2);
}

//after this i'll be inserting values in these variables into new temporary table that is having same structure so that my orignal data remain unchanged and new data as my need inserted into temporary table.

希望你能得到我的问题。

2 个答案:

答案 0 :(得分:0)

您需要迭代抛出每条记录并再次迭代抛出每个;分隔值。每条记录的idname都相同,但expanseamount会有所不同。插入查询的数量取决于;分隔值的数量

 $query="SELECT * FROM table";
 $result=mysql_query($query);

 while ($row=mysql_fetch_array($result)) 
{

    $id = $row["id"]; // duplicating for each 
    $name = $row['name']; // duplicating for each
    $expance_array = explode(';',$row["expanse"]); 
    $amount_array = explode(';',$row["amount"]); 

    /* count of expance_array and amount_array will be same always as per your idea */

    for($i=0;$i<count($expance_array);++$i) {

        $expanse = $expance_array[$i]; 
        $amount  =  $amount_array[$i];

        /* now insert $id   $name  $expanse  $amount  into the table*/
        $query2="INSERT INTO table2 (id, name , expanse, amount)  VALUES ($id,'$name','$expanse' , $amount");
        $result2=mysql_query($query2);

    }

}   

答案 1 :(得分:0)

对于数组中的每个项目,您都需要单独的INSERT。

function getInsertQueries($id, $expanse, $amount){
    $insertQueries = array();
    $expanses = array_unique(explode(";", $expanse));
    $amounts = array_unique(explode(";", $amount));
    if(count($expanses) == count($amounts)){
        for($i=0;$i<count($expanses);$i++){
            $insertQueries[] = "INSERT INTO table2 (id, expanse, amount) VALUES ('$id', '$expanses[$i]', '$amounts[$i]')";
        }
    }
    return $insertQueries;
}


$query="SELECT * FROM table";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)){
    $insertQueries = getInsertQueries($row["id"], $row["expanse"], $row["amount"]);
    foreach($insertQueries as $query){
        mysqli_query($query);
    }
}