我必须在 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 端和js 端函数
。但我的目标是应该很容易来回转换。
我也在 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 .
关于javascript - 关联数组到字符串和字符串到关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32858340/