简体   繁体   中英

post to form via php with array

i'm using sirportly for my support and i have the ability to post forms remotely via html, however i'm trying to integrate this into wordpress and so want to post this form from a plugin via curl/php the challenge i am having is to post into array objects:

eg the basic original HTML form generated by sirportly contains the following:

<input type='text' name='ticket[name]' id='form26-name' />
<input type='text' name='ticket[email]' id='form26-email' />
<input type='text' name='ticket[subject]' id='form26-subject' />
<textarea name='ticket[message]' id='form26-message'></textarea>

i know for basic form elements eg name=name, name=email etc i can do the following:

//create array of data to be posted
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
    $post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);

how do i do similar given that the elements need to be posted as 'ticket[name]' rather than just 'name'

EDIT/UPDATE - ANSWER

thanks to the answers below i came up with the solution, my issue wasn't getting access to the data from the array as i was recieving it a different way (but from an array all the same), but correctly encoding it in the post request, here is what i ended up with(note that i'm using gravity forms to get the data:

//numbers in here should match the field ID's in your gravity form
$post_data['name'] = $entry["1"];
$post_data['email'] = $entry["2"];
$post_data['subject'] = $entry["3"];
$post_data['message']= $entry["4"];

foreach ( $post_data as $key => $value) {
    $post_items[] = 'ticket[' . $key . ']' . '=' . $value;
}

$post_string = implode ('&', $post_items);

i just had to change the for loop to wrap the extra ticket[ and ] parts around the key for the post submission

foreach ( $post_data['ticket'] as $key => $value) {
    $post_items[] = $key . '=' . $value;
}

The form you listed above will result in this structure on server:

$_POST["ticket"] = Array(
   "name" => "some name",
   "email" => "some@thing",
   "subject" => "subject of something",
   "message" => "message text"
   );

So, $_POST["ticket"] is really your $post_data

You access the variable by this: $_POST['ticket']['name']

so if you want to see the value you should: echo $_POST['ticket']['name'];

to loop you go:

foreach($_POST['ticket'] as $key => $val){
    echo "Key =>  " . $key. ", Value => " . $val . "<br />";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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