1

I am currently having problem converting from Php array to Javascript array, My array in php looks like this:

    Array
(
    [0] => 2019-01-10-12:15,1
    [1] => 2019-01-10-12:15,1.5
    [2] => 2019-01-10-12:15,2.1
    [3] => 2019-01-10-12:15,1.3

)

And I have tried so many way I have found online but with no luck (such as json_encode and then JSON.parse). I need to convert above into a JS array. Struggle for a long time but could not figure out. Thank you!

5
  • 1
    var a = <?php echo json_encode($array); ?>; generally works (no quotes, no parsing the json), how did you try using it. IE> can you show us the Javascirpt code your trying to put it into. Commented Jan 16, 2019 at 22:35
  • I don't know why if I used json_encode() it automatically generate quotes on my Php array. It looked like jsArr = new Array("["2019-01-10-12:15,1\r","2019-01-10-12:15,1.5\r","2019-01-10-12:15,2.1\r","2019-01-10-12:15,1.3\r"]"); and giving me Uncaught SyntaxError: missing ) after argument list Commented Jan 16, 2019 at 22:54
  • What's this new Array( Not needed as it's already an array. Commented Jan 16, 2019 at 22:55
  • I have removed new Array(), and now I have "Uncaught SyntaxError: Unexpected number". Commented Jan 16, 2019 at 22:59
  • I found why, it is the problem of quotes, I should use " instead of '. Thanks Commented Jan 16, 2019 at 23:18

2 Answers 2

1

You should use in PHP:

$js = json_encode($obj);

In JavaScript:

var obj = JSON.parse(' ... YOUR JSON STRING FROM PHP ... '); 

==================

Your code:

var obj = new Array('["2019-01-10-12:15,1\r", .... "2019-01-10-12:15,1.3\r"]');

will result nested arrays.

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

Comments

0

If you're using PHP, json_encode should work perfectly - just assign it to a variable like so:

var myArray = <?php echo json_encode($myArray); ?>;

6 Comments

I have tried this method but it gave me Uncaught SyntaxError: missing ) after argument list var jsArr = new Array("["2019-01-10-12:15,1\r","2019-01-10-12:15,1.5\r","2019-01-10-12:15,2.1\r","2019-01-10-12:15,1.3\r"]");
In Javascript or in PHP?
It is giving me Uncaught SyntaxError: missing ) after argument list from JS, and after using js array. it looked like jsArr = new Array("["2019-01-10-12:15,1\r","2019-01-10-12:15,1.5\r","2019-01-10-12:15,2.1\r","2019-01-10-12:15,1.3\r"]");
Well, that is an error in your JavaScript code - and the array is working as well. Please post the rest of your JavaScript code so we may identify any additional errors.
This js file contains only this line so far, I was trying to convert from Php array into Js array then draw the graphthrough Highcharts.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.