Parsing javascript arrays in PHP

前端 未结 4 2006
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 05:47

I can\'t seem to figure out how to get a JS array into PHP.

What I have to work with looks like this:

var arrLow = [
{
\"e\": \"495864\",
\"rank\": \         


        
相关标签:
4条回答
  • 2021-01-05 06:17

    2 options:

    1. Just remove the var arrLow = at the front (might need a regex if its variable), and parse as json.
    2. Go for full on javascript parsing
    0 讨论(0)
  • 2021-01-05 06:20

    You can use json_decode() for this. The trick is to leave away the var arrLow = part (so that only the array itself is left). You can assign the value to the php variable $arrLowlike this:

    $js = '[ {"e" : "495864", ...';
    $arrLow = json_decode($js);
    

    A quick'n'dirty hack to remove the beginning would be to use the strstr() function.

    $js = strstr('var arrLow = [ {..', '[');
    
    0 讨论(0)
  • 2021-01-05 06:32
    //define javascript array 
    >var mainArray = {};    
    >       // inner loops
    mainArraySub['XXX'] = [];    
    
                 mainArray = JSON.stringify(mainArray);
          passing javascript array content in jquery ajax request as 
          $.ajax({
           type: "POST",
         data:{paramval:mainArray},
         dataType: "json",
        url: url,
       success: function(msg){
    
              }
          });    
    
    
    in POST request you will get as below
    
    {"row1":{"0":{"nnnn":"aaaa"},"1":{"Movie":"aaaa"},...}        
    
    // in a.php file call as below
    
    $Info = $_REQUEST['rowdata'];
    $tre = json_decode(stripslashes($Info),true);
    var_dump($tre);        
    
    0 讨论(0)
  • 2021-01-05 06:41

    According to the JSONLint validator this is valid JSON (without the var arrLow =). So any good json_decode() implementation should do the trick. Maybe the implementation you are using has certain limitations? The JSON.org website has a neat list of links to implementations of json_decode in PHP (and lots of other languages too). You can be sure to find one that does work.

    0 讨论(0)
提交回复
热议问题