简体   繁体   中英

JS array of literals to PHP

In JS, I have the following:

var languages = [{
    language: "da"
    listening: "A1"
}, {
    language: "en"
    listening: "B2"
}];

What I end up with, in PHP, after an $.ajax call is:

array(4) {
  [0]=>
  array(1) {
    ["language"]=>
    string(2) "da"
  }
  [1]=>
  array(1) {
    ["listening"]=>
    string(2) "A1"
  }
  [2]=>
  array(1) {
    ["language"]=>
    string(0) "en"
  }
  ...
}

What I need is something like this:

array(2) {
  [0]=>
  array(2) {
    ["language"]=>
    string(2) "da",
    ["listening"]=>
    string(2) "A1"
  }
  [1]=>
  array(2) {
    ["language"]=>
    string(2) "en",
    ["listening"]=>
    string(2) "B1"
  }
}

Is there a way to do this in a simple? Do I have to iterate and process it?

Use JSON.stringify to encode your data structure, send the resulting string as a single param, then decode it with json_decode($json, true) in PHP.

JS

var data = [
   { language: "da", listening: "A1"}, 
   { language: "en", listening: "B2"}
];
// ...
$.post(url, { data: JSON.stringify(data) }, function() { ... });

PHP

if (isset($_POST['data'])) {
  $data = json_decode($_POST['data'], true);
  // process this array of arrays
} 

I assume you mean something like this:

var languages = [{
    language: "da"
    listening: "A1"
}, {
    language: "en"
    listening: "B2"
}];

So you actually have two objects to transfer to PHP, packed into an array, right?. Try using JSON:

Create a JSON string and send it to the server:

$.ajax({
    url: '...',
    type: 'POST',
    data: { json: JSON.stringify(languages)}
});

On server side you'll now have the json string in $_POST['json'] and you can decode it with:

json_decode($_POST['json'], true); 

to get a (multidimensional) array, or

json_decode($_POST['json']); 

for an array containing two objects.

EDIT

If you have "Magic Quotes" on, you'll have to strip the backslashes first:

json_decode(stripslashes($_POST['json']), true); 

HTH,

Hello:

I think you should try out as follows javascript

{
    "languages": [
        {"language":"da","listening":"A1"},
        {"language":"en", "listening":"B2"}
    ]
}

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