10

In php I used json_encode(...) and then got the value in Javascript, looks as the following:

["float","float","float","float"]  // PS: This is a string...

And I would like to make this into a normal javascript array, like so:

Arr[0] // Will be float
Arr[1] // Will be float
Arr[2] // Will be float
Arr[3] // Will be float

How is this possible?

2

3 Answers 3

27

It sounds like you're retrieving a JSON string in JavaScript (perhaps via AJAX?). If you need to make this into an actual array value, you'd probably want to use JSON.parse().

var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);

If you're actually writing out a value into the page, rather than using AJAX, then you should be able to simply echo the output of json_encode directly, without quoting; JSON itself is valid JavaScript.

var myArray = <?php echo json_encode($myPhpArray); ?>;
1
  • very nice. I taught it is object in java script. Thanks for your answer Commented Dec 18, 2015 at 12:04
7
var myArray = <?= json_encode($myPhpArray); ?>;

Pretty simple. ;-)

Example:

<?php
  $myPhpArray = array('foo', 'bar', 'baz');
?>
<script type="text/javascript">
  var myJsArray = <?= json_encode($myPhpArray); ?>;
</script>

Should output (view-source):

<script type="javascript">
  var myJsArray = ["foo","bar","baz"];
</script>

Example

4
  • And that gives me the javascript array? Commented Dec 21, 2012 at 17:51
  • yes. it's taking an PHP variable and converting in to JSON which javascript will be able to parse and store. Commented Dec 21, 2012 at 17:52
  • 1
    As an explanation it might be helpful to note that JSON (JavaScript Object Notation) is a subset of the JavaScript language and so can be parsed successfully by any JavaScript interpreter. Commented Dec 21, 2012 at 17:58
  • Indeed, JSON!=JavaScript, it's just a serialized representation of data that JavaScript (and many other languages) can translate. Commented Dec 21, 2012 at 18:00
2

I reccomend using jquery. The php file should look as such ...

//location.php
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode($change);
?>

Then the jquery script ...

<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.