Use json_decode
to turn it into a JSON string. (an object in JavaScript), then traverse the object in JS. Traversing an array in JavaScript is not much different from doing it in PHP. All you have to do is pluck the array from the JSON object and then you can use a regular for loop.
<?php $myvalues = array(13,45,23,54,767,234,543,245); ?>
<script>
var myObject = <?php echo json_encode(array("payload" => $myvalues)); ?>;
var payload = myObject.payload;
/*
[ 13,
45,
23,
54,
767,
234,
543,
245 ]
*/
for(var i = 0; i < payload.length; i++) {
alert(payload[i];
}
</script>
Using Array.prototype.forEach
you can also traverse the object with an elegant callback function which gets 3 values: the value of the array at the current enumeration, the current numeric index, and a reference to array itself. Using this you wouldn't have to declare any iteration variables.But that probably won't work in some versions of IE if you're looking for a cross-browser solution.
<script>
var myObject = <?php echo json_encode(array("payload" => $myvalues)); ?>;
var payload = myObject.payload;
payload.forEach(function(val, index, array) {
alert(array[index]);
});
</script>
There are also other ways to traverse the object:
<script>
var myObject = <?php echo json_encode(array("payload" => $myvalues)); ?>;
var payload = myObject.payload;
var node;
while(node = payload.shift()) {
alert(node);
}
</script>