简体   繁体   English

获取分组的HTML数据到PHP数组? (像复选框的子元素一样)

[英]Get grouped HTML data to PHP array? (Like sub-elements of checkbox)

How to convert this form structure to a PHP array? 如何将此表单结构转换为PHP数组? I can also edit HTML, so every idea is good... 我也可以编辑HTML,所以每个想法都很好......

在此输入图像描述

If a checkbox is checked then this data is to push into a PHP array by saving, needed structure is: 如果选中了复选框,则此数据将通过保存推送到PHP数组中,所需的结构为:

0 =>
   'group' => 'group_a',
   'type' => 'type_yellow',
   'desc' => 'now to convert'
1 =>
   'group' => 'group_b',
   'type' => 'type_orange',
   'desc' => 'needed to order'

As example what I tried is to give by input element name as array like description[] but I cannot control if a checkbox is checked or not... 作为示例,我尝试的是通过input元素名称作为arraydescription[]但我无法控制是否选中了复选框...

Hmm. 嗯。 For checkboxes, standard behaviour is the value is only sent if the checkbox is checked. 对于复选框,标准行为是仅在选中复选框时才发送值。 So, a server side solution for this could be: 因此,服务器端解决方案可能是:

Firstly, Name the input fields as follows: 首先,将输入字段命名如下:

  • entries[][group]
  • entries[][type]
  • entries[][desc]

Or, alternatively 或者,或者

  • entries[0][group]
  • entries[0][type]
  • entries[0][desc]
  • entries[1][group]
  • entries[1][type]
  • entries[1][desc]
  • and so on.... 等等....

The values will be available as an array in $_POST[entries] , if you are using POST method. 如果您使用POST方法,这些值将作为$_POST[entries]的数组提供。

$entries = $_POST['entries'];

Now, we need to filter out entries for which it's corresponding checkbox is unchecked. 现在,我们需要过滤掉未选中相应复选框的entries We can use array_filter for that: 我们可以使用array_filter

$entries = array_filter($entries, function($entry) {
    return isset($entry['group']);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM