Reputation: 11
I have this string: '#d48888,abc.com,repeat,top left,scroll';
How do I convert this string to an array like this: Array('color'=>#d48888, 'href'=>abc.com, ... )
?
Upvotes: 1
Views: 68
Reputation: 1095
If you're going to use PHP, use explode(<delimeter>,string)
to convert your string into an array, and then add into the PHP array (which is really a map):
$str = "#d48888,abc.com,repeat,top left,scroll";
$aryStr = explode(",", $str);
$finalAry = [
"color" => $aryStr[0];
"href" => $aryStr[1];
//complete
];
Upvotes: 0
Reputation: 768
Try this,
First split the string on the comma basis:
var string = '#d48888,abc.com,repeat,top left,scroll';
var arrayOfString = str.split(',');
Use another array to store the key => Value pair:
var newArray = {};
newArray.color = arrayOfString[0];
newArray.href = arrayOfString[1];
newArray.action = arrayOfString[2];
newArray.top = arrayOfString[3];
newArray.scroll = arrayOfString[4];
Upvotes: 3
Reputation: 32354
Create a array with keys and then loop and save a object with the key and the value that you want
Try something like:
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/
Upvotes: 0
Reputation: 1095
I think you're looking for a javascript object, not an array.
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
Upvotes: 2