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....

link|improve this question

5  
I think that instead of encoding the array contents in your own format like that, you should use JSON. – Pointy Jun 25 '11 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 Jun 25 '11 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 Jun 25 '11 at 15:35
feedback

4 Answers

up vote 1 down vote accepted

PHP Code (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 everytime.

link|improve this answer
How do I then alert the entire contents of d? – DJDonaL3000 Jun 25 '11 at 16:41
Concatenating, I guess: alert(d.a+d.param2_customname+d.param1); – Ryan Casas Jun 25 '11 at 16:52
feedback

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>
link|improve this answer
feedback

You can use the split() Method in javascript :

http://www.w3schools.com/jsref/jsref_split.asp

link|improve this answer
feedback

You should look into JSON. PHP has functions to write JSON and javascript can decode such JSON objects and create native objects

link|improve this answer
+1, don't try and resolve the effect, resolve the cause instead. – Björn Jun 25 '11 at 15:31
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.