来自forminput的多维数组

时间:2013-07-19 15:57:07

标签: php arrays forms multidimensional-array

我认为我的解决方案是在一个多维数组中,但是如何...

如果我在HTML表单中有以下(或类似的)(例如简化)

<select name="Postage[]" id="Unique-ID">
    <option value="1">Postage Option 1</option>
    <option value="2">Postage Option 2</option>
    <option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />

<select name="Postage[]" id="Unique-ID">
    <option value="1">Other Postage Option 1</option>
    <option value="2">Other Postage Option 2</option>
    <option value="3">Other Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />

<select name="Postage[]" id="Unique-ID">
    <option value="1">Another Postage Option 1</option>
    <option value="2">Another Postage Option 2</option>
    <option value="3">Another Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />

如何将其存储到PHP数组中(以后我可以将其添加到我的数据库中) 到目前为止,我有下面的内容,但显然没有完成

if (isset($_POST['Postage'])) {
  if (is_array($_POST['Postage'])) {
    foreach($_POST['Postage'] as $PostateID=>$PostageOption){
      // this is where i am tottally stuck
      // need to assosiate postageID with a Postage Option and a PostagePrice
    }
  }
}

我很遗憾听起来很笨,但我还没有使用多维阵列的“Erika”时刻

我很感激任何建议

3 个答案:

答案 0 :(得分:0)

$_POST['Postage']不是多维数组。如果你var_dump($ _ POST ['Postage']),你可以很容易地看到它;它只是您选择中所有选定索引的数组:

array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(3) "1"
    [2]=>
    string(3) "1"
  }

以下是我输入的测试内容:

enter image description here

在这里,我使用for循环获得邮资和相关价格:

<?php
$n = count($_POST['Postage']);
for ($i = 0; $i < $n; ++$i)
{
    print $_POST['Postage'][$i] . " " . $_POST['PostagePrice'][$i] . "<br>";
}

打印:

1 1
2 2
2 3

答案 1 :(得分:0)

考虑您的输入数组如下:

<?
//Let your inputs be Postage1, Price1, Postage2, Price2...
//Then your Received POST will be..
$_POST = Array(
            "Postage" => Array( 0 => 'Postage1', 1 => 'Postage2', 2 => 'Postage3'),
            "PostagePrice"=> Array( 0 => 'Price1', 2 => 'Price2', 3 => 'Price3')
            );
//Now, you can see that index 0 points to a price of POSTAGE and so on 1 and 2..

//Store corresponding values in an Array.
$store = Array();

foreach($_POST['Postage'] as $PostateID=>$PostageOption){
    $store[$PostageOption] = $_POST['PostagePrice'][$PostateID];
}

print_r($store);

?>

答案 2 :(得分:0)

<?PHP
$final = array_combine($_POST['Postage'], $_POST['PostagePrice']);
?>

通过这种方式,您将在此数组中关联Postage和PostagePrice。