0

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>
RobG
  • 142,382
  • 31
  • 172
  • 209
Happy
  • 1,031
  • 10
  • 26

2 Answers2

0

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.

Marcel Burkhard
  • 3,453
  • 1
  • 29
  • 35
  • 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 Jan 14 '15 at 12:13
  • @Alnitak thanks for correcting your wrong statement and removing the downvote. – Marcel Burkhard Jan 14 '15 at 13:19
0
var arr = Object.keys(yourJsonvariable).map(function(k) { return yourJsonvariable[k] });
console.log(arr)
Priyank
  • 3,778
  • 3
  • 29
  • 48