解析错误:语法错误,意外' =>' (T_DOUBLE_ARROW),期待')'在...与foreach

时间:2014-10-29 11:26:35

标签: php mysql mysqli foreach

我有一个包含多个具有相同名称的输入字段的表单。当我发送此表单时,我收到错误。 Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' in。

  <input type="text"name="keuze[]">
 <input type="text"name="prijs[]">
 <input type="text"name="cent[]">


  foreach (array_combine($_POST['keuze'], $_POST['prijs'], $_POST['cent']) as $keuze => $prijs => $cent) {

 $price = $prijs.".".$cent;

 $query = "INSERT INTO res_sub_menu (
 name,
 price,
 owner) VALUES 
 (
 '$keuze',
 '$price',
 '$session->u_id'
 )";

 }

3 个答案:

答案 0 :(得分:1)

而不是

foreach (array_combine($_POST['keuze'], $_POST['prijs'], $_POST['cent']) as $keuze => $prijs => $cent) {

使用PHP的MultipleIterator

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($_POST['keuze']));
$mi->attachIterator(new ArrayIterator($_POST['prijs']));
$mi->attachIterator(new ArrayIterator($_POST['cent']));
foreach($mi as list($keuze, $prijs, $cent)) {
    ...
}

如果它抱怨在list($keuze, $prijs, $cent)中使用foreach()(需要PHP&gt; = 5.5.0),那么您可以使用

$mi = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
$mi->attachIterator(new ArrayIterator($_POST['keuze']), 'keuze');
$mi->attachIterator(new ArrayIterator($_POST['prijs']), 'prijs');
$mi->attachIterator(new ArrayIterator($_POST['cent']), 'cent');
foreach($mi as $details) {
    extract($details);
    ...
}

答案 1 :(得分:0)

尝试这样做:

$cnt = count($_POST["keuze"]);
for ($i = 0; $i < $cnt; $i++) {
    $price = $_POST["prijs"][$i] . "." . $_POST["cent"][$i];
    $query = "INSERT INTO res_sub_menu (name,price,owner) 
                    VALUES  ('" . mysqli_real_escape_string($link, $_POST['keuze'][$i]) . ",'" . mysqli_real_escape_string($link, $_POST['price']) . "','$session->u_id')";

    mysqli_query($link, $query);
}

避免sql注入。

答案 2 :(得分:0)

array_combine()一次只能对数组进行操作。它通过使用一个数组作为键而另一个数组为其值创建一个数组。

$array = array_combine($_POST['prijs'], $_POST['cent']);
$values = array();
foreach ($array as $prijs => $cent) {
    $values[] = $prijs.".".$cent;
}

//现在处理最终数据

foreach (array_combine($_POST['keuze'], $values) as $keuze => $price) {
    //run your query
}