Php 使用foreach获取除最后一个键和值对以外的所有键和值对
我有一个表单,有很多单选按钮,最后有一个隐藏字段 我将遍历所有输入值,将它们放入一个插入项中,如下所示:Php 使用foreach获取除最后一个键和值对以外的所有键和值对,php,Php,我有一个表单,有很多单选按钮,最后有一个隐藏字段 我将遍历所有输入值,将它们放入一个插入项中,如下所示: $count=count($_POST); $counter=0; $queryV="INSERT INTO `notes_value` ( `style_color`, `value` ) VALUES "; $sku = $_POST['number']; //this is the one value coming from a hidden input foreach (
$count=count($_POST);
$counter=0;
$queryV="INSERT INTO `notes_value` ( `style_color`, `value` ) VALUES ";
$sku = $_POST['number']; //this is the one value coming from a hidden input
foreach ($_POST AS $key => $value) {
if ($counter < $count -1 )
$queryV.= "('$sku', '$value'),";
elseif ($counter = $count -1 )
$queryV.= "('$sku', '$value');";
$counter++;
}
这是一个仅选择了一个单选按钮的示例。在这种情况下,我希望它只返回一个$sku,$value
对。我从不想要来自此foreach
的最后一个$key,$value
。所以我想看看这个:
INSERT INTO `notes_value` ( `sku`, `data` ) VALUES ('12595200010037', 'yes');
$counter应该从一开始吗
$counter=1;
也许我不理解这个问题,但从我的角度来看:
$queryV = "INSERT INTO `notes_value` ( `style_color`, `value` ) VALUES ";
$sku = $_POST['number'];
array_pop($_POST);
$values = array();
foreach ($_POST AS $key => $value)
{
$values[] = "('$sku', '$value')";
// use $key for another query
}
$queryV .= implode(', ', $values) . ';';
如果我理解,您希望构建一个查询并跳过数组中的最后一个键/值对。您有一行
elseif($counter=$count-1)
。首先,这应该是==
,但这可能是这里介绍的一个输入错误,而不是在实际代码中。其次,当$counter==$count-1
这实际上是最后一项,而不是倒数第二项。*要跳过最后一项,只需将其更改为$counter==$count-2
*为什么??因为数组索引从0开始,但数组中的项目计数从1开始。例如,如果一个数组有四个元素,那么该数组的长度为4,元素的索引为0、1、2和3。倒数第二个元素位于索引2 看看数组\u pop
因此,基本上在进入循环调用之前,array\u pop($\u POST)
。
也就是说,您不应该真正修改超球体(IMHO),因此您可能会看到:
$postedData = $_POST;
array_pop($postedData);
foreach ($postedData as $key => $value) {
...
包括此功能:
function insert( )
{
$args = func_get_args();
$table = $args[0];
unset( $args[0] );
$return = true;
foreach( $args as $set )
{
$columns = implode( '`,`', array_keys( $set ) );
$values = implode( "','", array_values( $set ) );
$return =& query( "INSERT INTO {$table} (`{$columns}`) VALUES ('{$values}')" );
}
return $return;
}
然后在代码中使用:
$data = Array(
'key1' => $value1,
'key2' => $value2
);
insert('table', $data);
对于您的实际解决方案,您将使用:
$data = $_POST;
array_pop($data); //Removes the last element in the array
insert('table', $data);
elseif($counter=$count-1)
——你是说elseif($counter=$count-1)
?啊,是的,这正是我需要的。非常感谢。这不会跳过第一个元素而不是最后一个元素吗?我不确定是否会基于($counter<$count-1)跳过第一个元素
$data = $_POST;
array_pop($data); //Removes the last element in the array
insert('table', $data);