简体   繁体   中英

associative php array from html data attributes and texts

<div class='title' data-x='car'>black</div>
<div class='title' data-x='home'>white</div>
<div class='title' data-x='train'>gold</div>

what is the easyest way to get an associative array on php side:

$arr = ['car' => 'black', 'home' => 'white', 'train' => 'gold'];

Here is the proposal that I have:

  1. Use jQuery to add and map the data in one object.
  2. Use Ajax for sending the data
  3. Take all posted variables and transfer it into your array

Code:

 $( document ).ready(function() { var data = {}; $('.title').map(function(){ data[$(this).data('x')] = $(this).html(); }).get(); $.ajax({ type: "POST", url: 'whatever.php', data: data, success: (response)=>{ console.log(response); } }); }); 
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <div class='title' data-x='car'>black</div> <div class='title' data-x='home'>white</div> <div class='title' data-x='train'>gold</div> 

And the file whatever.php :

$arr = [];
if($_POST) {
    foreach ($_POST as $k => $v) {
        $arr[$k] = $v;
    }
    var_dump($arr);
}

Here is the console output:

array(3) {
    ["car"]=>string(5) "black"
    ["home"]=>string(5) "white"
    ["train"]=>string(4) "gold"
}

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