admin管理员组

文章数量:1178539

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?

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?

Share Improve this question edited Jan 1, 2021 at 21:20 peterh 12.6k20 gold badges89 silver badges113 bronze badges asked Dec 21, 2012 at 17:49 Miguel PMiguel P 1,2927 gold badges24 silver badges49 bronze badges 2
  • if you passed the array back using json_encode() you have an array and you can index it by the method you showed... – scrappedcola Commented Dec 21, 2012 at 17:53
  • possible duplicate of Pass a PHP array to a JavaScript function – Mohammed Azharuddin Shaikh Commented Dec 22, 2012 at 9:19
Add a comment  | 

3 Answers 3

Reset to default 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); ?>;
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

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>

本文标签: Javascript Convert PHP Json into a javascript arrayStack Overflow