需要foreach跳过/忽略丢失的数组

时间:2013-10-12 13:04:31

标签: php

我有这个PHP代码用于插入来自我的数据;

$i = 1;
foreach ( $_POST['form'] as $val => $form ){   
    $Style = $_POST['form'][$i]['style'];
    $Dim= $_POST['form'][$i]['Dim'];
    $Colour= $_POST['form'][$i]['Colour'];
    $Quantity= $_POST['form'][$i]['Quantity'];

    $stmt = $db->prepare("INSERT INTO orders(Cus_ID, Style, Dimensions, Colour, Quantity) VALUES(:Cus_ID,:Style,:Dimensions,:Colour,:Quantity)");

    $stmt->execute(array(':Cus_ID' => $Cus_ID, ':Style' => $Style, ':Dimensions' => $Dim, ':Colour' => $Colour, ':Quantity' => $Quantity));  

    $i++;
} 

当我提交表单时,var_dump会给我这样的内容;

array (size=3)
  'form' => 
    array (size=3)
      1 => 
        array (size=4)
          'style' => string '0' (length=1)
          'Dim' => string '0' (length=1)
          'Colour' => string '0' (length=1)
          'Quantity' => string '' (length=0)
      2 => 
        array (size=4)
          'style' => string '0' (length=1)
          'Dim' => string '0' (length=1)
          'Colour' => string '0' (length=1)
          'Quantity' => string '' (length=0)
      3 => 
        array (size=4)
          'style' => string '0' (length=1)
          'Dim' => string '0' (length=1)
          'Colour' => string '0' (length=1)
          'Quantity' => string '' (length=0)
  'submit' => string 'Place Order' (length=11)

一切都很好,花花公子,但是当我删除部分表格时,提交的aray会结束这样的事情;

array (size=2)
  'form' => 
    array (size=2)
      1 => 
        array (size=4)
          'style' => string '0' (length=1)
          'Dim' => string '0' (length=1)
          'Colour' => string '0' (length=1)
          'Quantity' => string '' (length=0)
      3 => 
        array (size=4)
          'style' => string '0' (length=1)
          'Dim' => string '0' (length=1)
          'Colour' => string '0' (length=1)
          'Quantity' => string '' (length=0)
  'submit' => string 'Place Order' (length=11)

php试图进入不存在的'2nd'数组,是否可以让php'skip / ignore'任何缺失的数组(数组是无限的,任何随机数都可能丢失) )

2 个答案:

答案 0 :(得分:3)

是的,如果没有设置当前索引,只需continue即可。

但是,您根本没有理由使用$i。我们会编写foreach循环,以便您以$form的形式访问每个表单,因此只需使用$form

foreach ( $_POST['form'] as $val => $form ){  
    # No! 
    $Style = $_POST['form'][$i]['style'];
    $Dim   = $_POST['form'][$i]['Dim'];

    # Yes!
    $Style = $form['style'];
    $Dim   = $form['Dim'];

    #...
}

答案 1 :(得分:2)

在foreach中,您不需要使用$i$val是子阵列的关键。 $form是子数组,可以用作:

foreach ( $_POST['form'] as $val => $form ){   
    $Style = $form['style'];
    $Dim= $form['Dim'];
    $Colour= $form['Colour'];
    $Quantity= $form['Quantity'];

    $stmt = $db->prepare("INSERT INTO orders(Cus_ID, Style, Dimensions, Colour, Quantity) VALUES(:Cus_ID,:Style,:Dimensions,:Colour,:Quantity)");

    $stmt->execute(array(':Cus_ID' => $Cus_ID, ':Style' => $Style, ':Dimensions' => $Dim, ':Colour' => $Colour, ':Quantity' => $Quantity));  

}

所以,为了回答你的问题,foreach永远不会丢失数组。它遍历数组元素,因此,如果数组有两个元素,它将迭代两次。如果数组有三个元素,它将迭代3次,依此类推。