javascript - 关联数组到字符串和字符串到关联数组

标签 javascript php jquery

我必须在 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/

相关文章:

jquery - 使用 jquery minicolors 更改颜色

javascript - 触发点击 iframe

javascript - 基于数组插入html

javascript - TypeError : utils. requestSendSMSPermission 不是函数

javascript - jQuery 提交问题

php - 在 php echo 中加载 Bootstrap

javascript - 语法错误: unterminated string literal in javascript

Jquery 事件仅在文档就绪时工作

javascript - Preg_match 到正则表达式等效表达式以匹配任何 Unicode 字母

javascript - 如何更改 <a href""></a> 标签超链接部分内的图像大小