0

我想遍历其中包含 $i 变量的数组的值,

我的数组代码如下所示,

foreach($fields_names as $k => $v) {
      $handle_data[] ='$rowdata[$i][$fields_names[\''.$v.'\']]';
}

for($i=0;$i<$number_rows_excel;$i++){

$sql.= "('".implode("','", array_values($handle_data))."'),". "<br/>";

        }

当我回显 $sql 时,我会变成这样,

INSERT INTO eximport (`S.No`, `Patent#`, `Title`) VALUES ('$rowdata[$i][$fields_names['S.No']]','$rowdata[$i][$fields_names['Patent#']]','$rowdata[$i][$fields_names['Title']]')

它应该像这样显示

INSERT INTO eximport (`S.No`, `Patent#`, `Title`) VALUES ('$rowdata[0][$fields_names['S.No']]','$rowdata[0][$fields_names['Patent#']]','$rowdata[0][$fields_names['Title']]')

如何使用变量 $i 循环遍历数组值?

4

3 回答 3

1

我使用了这段代码来帮助我插入行,为插入的每个值附加“,”

 foreach($val_ary as $new_data_string){
    $newArray[] = implode("','",$new_data_string);
        }

//Inserting data into the table     
        for($tr=0;$tr< $data->sheets[0]['numRows']-2;$tr++)
        {
         $sql ="INSERT INTO eximport($fieldnames)values('$newArray[$tr]')";
         mysql_query($sql) or die("Error in Query: " . mysql_error());  
         //$p1 = $db->insert_id;
         }
于 2012-12-19T05:21:41.927 回答
0

我假设您不想将$rowdata[]部分写入查询,但是该数组条目的实际值?

所以,你应该像这样简单地嵌套你的循环。请记住,您正在循环每个字段,这意味着您不需要对数据进行任何内爆。我假设您的数据集在数组内,$data而 $field_names 只是一个字段名列表。:

$data = array(
   array("name" => "DataSet1", "value" => 56),
   array("name" => "DataSet2", "value" => 5)
);

$field_names = array("name","value");

$sql = "INSERT INTO table (";
$sql .= implode($fields_names,",");
$sql .= ")VALUES";

for($i=0; $i<count($data); $i++){
   $sql .= "(";
   foreach($fields_names as $k => $v) {
      $sql.= "'".$data[$i][$v]."',";

   }
   //remove trailing ","
   $sql = substr($sql,0,-1);
   $sql .= "),";
}
//remove trailing ","
$sql = substr($sql,0,-1);

这将产生:

INSERT INTO table (name,value)VALUES('DataSet1','56'),('DataSet2','5')

于 2012-12-06T06:30:12.340 回答
0

尝试这个

$i=0;
foreach($fields_names as $k => $v) {
    $handle_data[] ='$rowdata['.$i.'][$fields_names[\''.$v.'\']]'; $i++;
}
于 2012-12-06T05:49:54.560 回答