user3691635 user3691635 - 6 months ago 17
PHP Question

PHP Form Fields with Int as name for json array

I have the following code which works well to get specific values and strip the strings like I need. However, I want to grab the fields with an int for the name and place those into an json array under my custom fields section. How can I iterate over the fields and find all fields with an int for the name then use that as the json ID with the passed value as the json value? IE:

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


JSON encoded:

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


What I have now:

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'))));

Answer

Your code is processing only $POST keys that start with z. To fix, use this.

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

I have added || gettype($key) == 'integer' to your if clause to process integer keys as well.