如何在数组中设置键值?

时间:2016-03-09 05:04:23

标签: php jquery arrays

我有这个字符串:'#d48888,abc.com,repeat,top left,scroll';

如何将此字符串转换为如下数组:Array('color'=>#d48888, 'href'=>abc.com, ... )

4 个答案:

答案 0 :(得分:3)

试试这个,

首先以逗号为基础拆分字符串:

var string = '#d48888,abc.com,repeat,top left,scroll';
var arrayOfString =   str.split(',');

使用另一个数组存储key =>价值对:

var newArray = {};
newArray.color = arrayOfString[0];
newArray.href = arrayOfString[1];
newArray.action = arrayOfString[2];
newArray.top = arrayOfString[3];
newArray.scroll = arrayOfString[4];

答案 1 :(得分:2)

我认为你正在寻找一个javascript对象,而不是一个数组。

var tmpObj = {};
var str = '#d48888,abc.com,repeat,top left,scroll';

var aryStr = str.split(','); //Splits the string on a delimeter
tmpObj.color = aryStr[0]; //sets the 'color' property
tmpObj.href = aryStr[1]; //sets the 'href' property
//Complete object

console.log(aryStr); //prints out the object and its properties

答案 2 :(得分:0)

使用键创建一个数组,然后循环并使用键和所需的值保存一个对象

尝试类似:

var string_array= '#d48888,abc.com,repeat,top left,scroll'.split(',');
var array_key=["color","href","background-repeat","background-position","overflow"];
var newobj = {};
$.each(string_array,function(i,v){
 newobj[array_key[i]] = v;
});

https://jsfiddle.net/1qbu4brs/

答案 3 :(得分:0)

如果您要使用PHP,请使用explode(<delimeter>,string)将字符串转换为数组,然后添加到PHP数组(实际上是地图)中:

PHP explode() documentation

$str = "#d48888,abc.com,repeat,top left,scroll";
$aryStr = explode(",", $str);

$finalAry = [
    "color" => $aryStr[0];
    "href" => $aryStr[1];
    //complete
];