我遇到了两个用于将数据插入数据库的foreach循环的问题。
这就是我目前所拥有的:
$to_ord = explode("**", $this->to_ord[$i]);
$i=0;
foreach ($to_ord as $tord) {
$sql3 = "INSERT INTO
temporders (order_description)
VALUES (:order_description)";
$st3 = $conn->prepare ( $sql3 );
$st3->bindValue( ":order_description", $tord[$i], PDO::PARAM_STR );
$st3->execute();
$i++;
}
$qo_ord = explode("**", $this->qo_ord[$i]);
$i=0;
foreach ($qo_ord as $qord) {
$sql4 = "INSERT INTO
temporders (order_description)
VALUES (:order_description)";
$st4 = $conn->prepare ( $sql4 );
$st4->bindValue( ":order_description", $qord[$i], PDO::PARAM_STR );
$st4->execute();
$i++;
}
基本上,代码获取信息源并将其插入表中。然而第二个没有运行,我把它缩小到$ i和$ ++使用,因为如果我从第一个删除$ i和$ i ++(第一个显然不会运行它)第二个脚本会工作,但一旦我回到$ i,第二个就不会再工作了。
有没有可以解决这个问题?两个阵列的大小不一样。
非常感谢任何帮助。
伊恩
答案 0 :(得分:1)
我希望我可以通过以下示例澄清这一点:
$qo_ord = array(
array( "0 - first value", "0 - second value", "0 - third_value", "0 - fourth value", "0 - fifth value" ),
array( "1 - first value", "1 - second value", "1 - third_value", "1 - fourth value", "1 - fifth value" ),
array( "2 - first value", "2 - second value", "2 - third_value", "2 - fourth value", "2 - fifth value" ),
array( "3 - first value", "3 - second value", "3 - third_value", "3 - fourth value", "3 - fifth value" ),
array( "4 - first value", "4 - second value", "4 - third_value", "4 - fourth value", "4 - fifth value" ),
);
$i=0;
foreach ( $qo_ord as $qord ) {
//$qord is now an element of your array ie. in the first loop => array( "0 - first value", "0 - second value"
echo $qord[$i]."<br>";
$i++;
}
使用上面的代码,您可以像这样浏览数组:
|X| | | | |
-----------
| |X| | | |
-----------
| | |X | | |
-----------
| | | |X| |
-----------
| | | | |X|
下一个例子:
// if you want to get the first item just use [0]
foreach ( $qo_ord as $qord ) {
//$qord is now an element of your array ie. in the first loop => array( "0 - first value", "0 - second value"
echo $qord[0]."<br>";
}
使用上面的代码,您可以像这样浏览数组:
|X| | | | |
-----------
|X| | | | |
-----------
|X| | | | |
-----------
|X| | | | |
-----------
|X| | | | |