获取foreach中的当前数组键

Ges*_*ltO 4 php forms arrays foreach

好的,我正在为我的雇主建立一些东西供他们输入产品,他们有非常具体的要求.我有一个动态生成字段的表单,如此...(显然不是要遵循的确切代码,但示例在概念上是相同的)

<input type="text" name="attribute[20]"> inputted value = height
<input type="text" name="attribute[27]"> inputted value = width
Run Code Online (Sandbox Code Playgroud)

数字是根据数据库中的内容生成的,因此20与"宽度"27相关,例如与"高度"相关.

因此,一旦用户输入值,我需要将这些值放入数据库......或者在测试中,回显出来.

foreach ($_POST['attribute'] as $attributes){
echo key($attributes).' '.$attributes.'<br>';
}
Run Code Online (Sandbox Code Playgroud)

那应该输出......

20高度值
27宽度值

而是输出

 高度值
 宽度值

到底是怎么回事?我有类似的东西...但略有不同,因为定义的数字可以有多个输入....这是完美的.

<input type="text" name="option[][20]"> inputted value = option 1
<input type="text" name="option[][20]"> inputted value = option 2
<input type="text" name="option[][27]"> inputted value = option 1

foreach ($_POST['option'] as $options){
echo key($options).' ';
foreach ($options as $option){
echo $option.'<br>';
}
Run Code Online (Sandbox Code Playgroud)

哪个输出完美......

20选项1
20选项2
27选项1

我不明白为什么更复杂的一个工作而更简单的工作没有,我错过了一些明显的东西吗?我知道我有一些有点非正统的编码方法与一些相比,但它是什么,大声笑.任何帮助将不胜感激.

编辑:根据要求转储Var

array(22){["pID"] => string(12)"test product"["pPrice"] => string(0)""["pName"] => string(0)""["pRRP" ] => string(0)""["pPostSize"] => string(0)""["pOurPrice"] => string(0)""["pEstDelivery"] => string(0)""[" pWeight"] => string(0)""["pEAN"] => string(0)""["pOrder"] => string(0)""["pStock"] => string(0)"" ["pManufacturer"] => string(0)""["pType"] => string(13)"Shower Valves"["pRange"] => string(0)""["cat"] => array( 2){[0] => string(2)"72"[1] => string(2)"23"} ["attribute"] => array(2){[ 0 ] => string(5)" width "[1] => string(6)"height"} ["option"] => array(3){[0] => array(1){[ 11 ] => string(6)" works1 "} [1] => array(1){[ 10 ] => string(6)" works1 "} [2] => array(1){[ 10 ] => string(6)" works2 "}} ["pLongdescription "] => string(0)""["meta_description"] => string(0)""["meta_keyword"] => string(0)""["meta_title"] => string(0)""[ "action"] => string(6)"create"}

大胆的部分,是我在第二个例子中成功出现的部分.但是你可以看到粗体斜体,返回0而不是实际在表单名称值中的20.

Jim*_*Jim 13

<input type="text" name="attribute[20]"> inputted value = height
<input type="text" name="attribute[27]"> inputted value = width

foreach ($_POST['attribute'] as $attributes){
    echo key($attributes).' '.$attributes.'<br>';
}
Run Code Online (Sandbox Code Playgroud)

请注意,您在post中循环遍历属性数组.$ attributes是每个字段的值(因此不是数组).

而不是使用key()尝试:

foreach ($_POST['attribute'] as $attributeKey => $attributes){
    echo $attributeKey.' '.$attributes.'<br>';
}
Run Code Online (Sandbox Code Playgroud)