blogjunkie
blogjunkie

Reputation: 237

How to store a variable in an array?

I have data from a form submission stored in a variable called $post_data. When I do print_r($post_data); I get the following array:

Array
(
    [element_3] => John Doe
    [element_2] => [email protected]
    [element_14] => City
    [element_15] => Country
    [form_id] => 1
    [submit] => Submit
);

I want to store some of the fields in another array to pass to another script. Will my code below work? If not, how do I fix it?

$submitted_data = array(
    'Fields' => array(
        array(
            'Key' => 'Name',
            'Value' => $post_data['element_3']
        )
        array(
            'Key' => 'Email',
            'Value' => $post_data['element_2']
        )
    )
)

Also, a PHP noob question, do I need another comma (,) in between the Name and Email array?

Thanks!

Upvotes: 2

Views: 16950

Answers (2)

hawkstah
hawkstah

Reputation: 26

I'm not exactly sure why you would want to do this, but depending on the field name you can consider using loops to help automate the entire process.

$field_map = array(
    'element_3'  => 'Name',
    'element_2'  => 'E-mail',
    'element_14' => 'City',
    'element_15' => 'Country'
);

$submitted_data = array('fields' => array());    
foreach ( $field_map as $key => $label) 
{
    $submitted_data['fields'][] = array(
        'key'   => $key,             // e.g. element_2
        'label' => $label,           // e.g. E-mail
        'value' => $post_data[$key]  // e.g. [email protected]
    );
}

This separates the storage/mapping of key/label pairs from the part which processes it, making it easier to maintain and modify in the future.

Upvotes: 1

MattBianco
MattBianco

Reputation: 1531

Another way might be (depending on how "fixed" the second script is, if you can alter it).

$submitted_data['Name']=$post_data['element_3'];
$submitted_data['Email']=$post_data['element_2'];

To get a result more like the one in your question:

$submitted_data['Fields']['0']['Key']='Name';
$submitted_data['Fields']['0']['Value']=$post_data['element_3'];
$submitted_data['Fields']['1']['Key']='Email';
$submitted_data['Fields']['1']['Value']=$post_data['element_2'];

Upvotes: 0

Related Questions