Convert String to Array in JavaScript
I have a PHP String like this:
$string = 'a => 1 , b => 2 , c => 3 , d => 4';
which I have built from data from a database, where each "x => y"
represents an associative relationship between x and y.
I am then transferring this string to the html doc开发者_运维技巧ument (JQuery) and attempting to make an array out of it in JavaScript, so that I may process on the client side.
QUESTION:
Is it possible to create a JavaScript Array out of a string?
For example I need to be able to retrieve the values in the array by calling'alert(array["c"]);'
or something similar.
NOTE - feel free to alter the semantics of the above string ($string) as necessary.
Any help appreciated guys....
You should look into JSON. PHP has functions to write JSON and javascript can decode such JSON objects and create native objects
PHP Code
(for instance, a file, like array.php):
$array=array(
'a'=>'I am an A',
'param2_customname'=>$_POST['param2'],
'param1'=>$_POST['param1']
);
echo json_encode($array);
jQuery code:
$.post('array.php', {'param1': 'lol', 'param2': 'helloworld'}, function(d){
alert(d.a);
alert(d.param2_customname);
alert(d.param1);
},'json');
You can use this for arrays, remember the 'json'
tag at the end of the request everytime.
You can use the split() Method in javascript :
http://www.w3schools.com/jsref/jsref_split.asp
I would do this
<?php
$string = "a => 1, b => 2";
$arr1 = explode(",",$string);
$arr2 = array();
foreach ($arr1 as $str) {
$arr3 = explode("=>", $str);
$arr2[trim($arr3[0])] = trim($arr3[1]);
}
?>
<script type="text/javascript">
$(document).ready(function(){
var myLetters = new Array();
<?php foreach($arr2 as $letter => $number): ?>
myLetters['<?php echo $letter; ?>'] = "<?php echo $number; ?>";
<?php endforeach; ?>
});
</script>
which will output this
<script type="text/javascript">
$(document).ready(function(){
var myLetters = new Array();
myLetters['a'] = "1";
myLetters['b'] = "2";
});
</script>
精彩评论