Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I get the php array from java script using json_encode. how to convert this array into java script array

code.

<?php 
  $dataArray = array("Task","Hours Per Day");
  $arr1 = array("Work","Eat","Commute","Watch TV","Sleep");
  $arr2 = array(110,2,2,2,7);
?><html><head></head><body>
  <script type="text/javascript">
    var jArray =<?php echo json_encode($dataArray); ?>;
    var jArray1 =<?php echo json_encode($arr1); ?>;
    var jArray2 =<?php echo json_encode($arr2); ?>;
  </script>
</body>
</html>
share|improve this question

marked as duplicate by Alnitak 7 hours ago

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2  
this should be closed simply because of the sheer lack of research effort –  Alnitak 7 hours ago
    
So what markup does this actually generate? –  RobG 7 hours ago
    
@RobG why is that relevant? –  Alnitak 7 hours ago
    
@Alnitak—presumably the result of <?php echo json_encode($dataArray); ?> is (intended to be) a javascript array literal. Whether or not it produces the expected result will help. –  RobG 7 hours ago

2 Answers 2

var arr = Object.keys(yourJsonvariable).map(function(k) { return yourJsonvariable[k] });
console.log(arr)
share|improve this answer

You don't need to.

<script type="text/javascript">
    var jArray = <?php echo json_encode($dataArray); ?>;
    console.log(jArray);
</script>

Check the console output (F12 in most browsers), it's already an array.

That's because json_encode produces json which is at the same time an array literal in javascript.

share|improve this answer
1  
actually, it is Ok after all - the string literal (without the quotes) will be inserted into the JS source at which point it will actually be a well formed array. –  Alnitak 7 hours ago
    
@Alnitak thanks for correcting your wrong statement and removing the downvote. –  Marcel Burkhard 6 hours ago

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