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 document (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....
-
5I think that instead of encoding the array contents in your own format like that, you should use JSON.Pointy– Pointy2011年06月25日 15:27:14 +00:00Commented Jun 25, 2011 at 15:27
-
Are you starting with a PHP string like that, or do you have an array in your PHP code that you are then converting to that string?Dogbert– Dogbert2011年06月25日 15:30:45 +00:00Commented Jun 25, 2011 at 15:30
-
I agree, use JSON. Create a map in PHP of the key/value pairs and use json_encode() to transform it.Kwebble– Kwebble2011年06月25日 15:35:35 +00:00Commented Jun 25, 2011 at 15:35
4 Answers 4
You should look into JSON. PHP has functions to write JSON and javascript can decode such JSON objects and create native objects
1 Comment
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.
2 Comments
You can use the split() Method in javascript :
Comments
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>
Comments
Explore related questions
See similar questions with these tags.