0

I get the php array from javascript using json_encode. how to convert this array into javascript 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>
4
  • 2
    this should be closed simply because of the sheer lack of research effort Commented Jan 14, 2015 at 12:05
  • So what markup does this actually generate? Commented Jan 14, 2015 at 12:13
  • @RobG why is that relevant? Commented Jan 14, 2015 at 12:13
  • @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. Commented Jan 14, 2015 at 12:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 thanks for correcting your wrong statement and removing the downvote.
0
var arr = Object.keys(yourJsonvariable).map(function(k) { return yourJsonvariable[k] });
console.log(arr)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.