简体   繁体   中英

How can I post array keys that have special characters?

I have a form that contains some special characters as the keys. Below is an example:

<input type="text" name="skills[React.js]" placeholder="Years" class="form-control">
<input type="text" name="skills[Responsive-Web-Design-(RWD)]" placeholder="Years" class="form-control">

When I post the form I get 0:value, 1:value Instead of React.js:value, Responsive-Web-Design-(RWD): value

Are there any workarounds?

To get desired output, text input should be like this

<input type="text" name="skills[]"  
 placeholder="Years" class="form-control"
 value="React.js"> 

 <input type="text" name="skills[]"   
  placeholder="Years" class="form-control"
  value="Responsive-Web-Design-(RWD)">

And in server side, received these values

<?php 
    if(isset($_POST['skills'])){
      $value1=$_POST['skills'][0];
      $value2=$_POST['skills'][1];
     }
 ?>

Here's how you could do it using vanilla PHP

<?php

$topics = [
    1 => 'React.js',
    2 => 'Responsive-Web-Design-(RWD)'
]

?>

<?php foreach ($topics as $key => $label) { ?>
    <input type="text" name="skills[<?php echo $key; ?>]" placeholder="Years" class="form-control">
<?php } ?>

The submitted request should contain:

[
    'skills' => [
        1 => 'first field value',
        2 => 'second field value',
    ]
]

So to get it the way you want it:

$skills = [];

foreach($_POST['skills'] as $key => $value) {
    $skills[$topics[$key]] = $value;
}

the $result array would now contain:

[
    'React.js' => 'value 1',
    'Responsive-Web-Design-(RWD)' => 'value 2'
]

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