PHP表单字段,其中Int作为json数组的名称

时间:2016-06-06 03:51:34

标签: php arrays json

我有以下代码,可以很好地获取特定值并删除我需要的字符串。但是,我想获取名称为int的字段,并将它们放入我的自定义字段部分下的json数组中。如何迭代字段并查找名称为int的所有字段,然后将其用作json ID,并将传递的值作为json值? IE:

input type="text" name="24349163" value="Here"

JSON编码:

"id"=>'24349163', "value" =>'value of the field I need'

我现在拥有的:

foreach($_POST as $key => $value){
    if(preg_match('/^z_/i',$key)){
        $arr[strip_tags($key)] = strip_tags($value);
    }
}
$create = json_encode(array('ticket' => array('subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']), 'requester' => 
array('name' => $arr['z_name'], 'email' => $arr['z_requester']), 
'custom_fields' => array("id"=>'24349163', "value" =>'Here'))));

邮寄表格:

 <form id="zFormer" method="post" action="tickets.php" name="zFormer">
    <table>
    <tr>
    <td valign="top">
     <label for="z_name">Your Name:</label>
     <input type="text" value="John Doe" name="z_name" />
    </td>
    <td valign="top">
     <label for="z_requester">Your Email Address: </label>
     <input type="text" value="john@domain.com" name="z_requester" />
    </td>
</tr>
<tr>
    <td valign="top">
     <label for="z_subject">Title/Subject: </label>
     <input type="text" value="Who needs a subject?" name="z_subject" />
    </td>
    <td valign="top">
     <label for="z_description">Summary Description:</label> 
     <textarea name="z_description">Systems are down</textarea>
    </td>
</tr>
<tr>
    <td valign="top">
     <label for="24275273">Incident Start Date:</label><br/> 
     <input type="date" name="24275273" value="" />
    </td>
    <td valign="top">
     <label for="24275293">Incident Start Time:</label><br/> 
     <input type="time" name="24275293" value="" />
    </td>
</tr>

2 个答案:

答案 0 :(得分:1)

我不是100%确定我理解这个问题,但听起来就像你需要在foreach中添加其他内容一样:

foreach($_POST as $key => $value){
    if(preg_match('/^z_/i',$key)){
        $arr[strip_tags($key)] = strip_tags($value);
    }
    elseif(is_numeric($key)) {
        $arr['ticket']['custom_fields'] =   array('id'=>$key,'value'=>$value);
        /*
        if you expect multiple id values:
        $arr['ticket']['custom_fields'][]   =   array('id'=>$key,'value'=>$value);
        */
    }
}

答案 1 :(得分:1)

您的代码仅处理以开头的$ POST键。要修复,请使用此功能。

foreach($_POST as $key => $value){
    if(preg_match('/^z_/i',$key) || gettype($key) == 'integer'){
    $arr[strip_tags($key)] = strip_tags($value);
    }
}

我已将|| gettype($key) == 'integer'添加到if子句中以处理整数键。