我必须在an associative array to string中转换php。我这样做是

  $cookieValue = http_build_query(arr,'','SEP');


我正在使用setcookie设置cookie。

  setcookie('subs',$cookieValue,0,'/');


JS端的Cookie看起来像

 "emailID=a1%40a.comSEPmaths=0SEPphysics=1SEPchemistry=2SEPbotany=3SEPzoology=4SE
 Ptamil=5SEPenglish=6SEPpolity=7SEPgk=8SEPhistory=9"


我试图将其转换回关联数组。

我刚试过JSON.parse。这对我来说没有用。

我可以自由更改两个php side and js side functions。但我的目标是,前后转换应该很容易。

我也在php上尝试了implode

最佳答案

尝试这个:

var a = "emailID=a1%40a.comSEPmaths=0SEPphysics=1SEPchemistry=2SEPbotany=3SEPzoology=4SEPtamil=5SEPenglish=6SEPpolity=7SEPgk=8SEPhistory=9";

 var myarr = {};
var sep = "SEP";
 a.split(sep).forEach(function(item){
     var sepp = item.indexOf("=");
     myarr[item.substr(0,sepp)] = decodeURIComponent(item.substr(sepp+1));
 });
console.log(myarr);


这是demo

09-10 10:24
查看更多