douchang8219 2014-08-28 17:07
浏览 14
已采纳

我如何在数组中存储表单值?

How would I be able to append data to an array from a form?

A list is generated according to the data found in the database. Each row has a part number and a QTY text field for the user to edit:

+--------+----------+
| Part # | QTY      |
+--------+----------+
| 123    | [0]      |
+--------+----------+
| 124    | [2]      |
+--------+----------+
| 125    | [15]     |
+--------+----------+
|        | [Submit] |
+--------+----------+ 

The logic I have so far is:

If QTY = 0 { 
ignore 
} else {
append values to array object and store array under "parts" session
} 

An issue I'm running into is when the form is submitted, it grabs the last part and qty value in the form. I need to somehow make each row unique for the form and input that form data into array.

I plan on after the user adds all the parts and qtys to the array, the array is then submitted into a database.

Is there an easier way of doing this?

EDIT:

Grabs the part number and submits the qty value via the form.

<input type="text" name="item['.$row['Part'].'][qty]" size="2" value="0"/>

So it would look like this:

123 => 0, 124 => 2, 125 => 15

And if value in form is set, map the array. I also used the array_filter() function to get rid of the 0 qty parts:

function show_Names($e)
    {
        return "$e[qty]";
    }
        if(isset($_POST['item'])) {
        $c = array_filter(array_map("show_Names", $_POST['item']));
    }

And stored it in a session this way. If nothing is set so far, set a new session. If something is set, then just add onto the array:

if(isset($_SESSION['parts'])) {             
        if(isset($c)) {
        $_SESSION['parts']=$_SESSION['parts']+$c;
        }
    } else {
        if(isset($c)) {
        $_SESSION['parts']=$c;
        }
    }

Hope this helps anyone else tackling a similar issue.

  • 写回答

2条回答 默认 最新

  • duanchouyi6730 2014-08-28 17:14
    关注

    Yes. By naming the fields like:

    <input type="text" name="item[0][name]" />
    <input type="text" name="item[0][email]" />
    
    <input type="text" name="item[1][name]" />
    <input type="text" name="item[1][email]" />
    
    <input type="text" name="item[2][name]" />
    <input type="text" name="item[2][email]" />
    

    And php script:

    function show_Names($e)
    {
      return "The name is $e[name] and email is $e[email], thank you";
    }
    
    $c = array_map("show_Names", $_POST['item']);
    print_r($c);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突