在PHP格式的输入字段中传递关联数组

时间:2015-02-18 01:37:25

标签: php arrays forms post

我想知道在输入字段内传递关联数组的最佳和最简单的方法。到目前为止,我已经完成了这一切,这一切都开始变得混乱,难以处理。

$dish_result = $obj->getAll_dish();// this returns array all the rows in dish table
<form action='order_process.php' method='post'>
   foreach ($dish_result as $dish){
     echo '<input id="" name="dish_name[]" type="checkbox" value="'. $dish['dish_name'].'">';
     echo '<input id="" name="dish_number[]" type="checkbox" value="'. $dish['dish_number'].'">';         
     }
</form>

现在在order_process.php我有

 foreach($_POST['dish_name'] as $dish){
        echo $dish;
  }
 foreach($_POST['dish_number'] as $num){
       echo $num;
 }

我想要的是一个关联数组,但我怎样才能动态地将它与表单相关联。换句话说,我想在order_process.php上实现这个目标。

 $dishes = array(
       //'dish_name' => dish_number
      'chickencurry' => '70',
      'onionbhajis'  =>  '22'
       // and so on. 
  );

非常感谢你。

2 个答案:

答案 0 :(得分:1)

首先创建一个分组名称,然后获取那种结构,将菜名称作为键,然后value属性保存数字。基本思路是:

name="dish[dishname]" value="dish_number"

就像这样:

echo '<input id="" name="dish['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'" />';

当您提交所有选中的复选框时,它应该是:

Array
(
    [chickencurry] => 1
    [onionbhajis] => 2
)

order_process.php页面上,只需像平常一样调用它:

$dishes = $_POST['dish'];
foreach($dishes as $dish_name => $dish_number) {

}

Sample Output

答案 1 :(得分:0)

您可以为数组postdata添加索引。试试这个:

  foreach ($dish_result as $dish){
      echo '<input id="" name="dishes['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'">'; 
  }

当您回发时,您的数据将成为已检查元素的关联数组。