1

I've got the following code:

  $data = array(
     "1421852400000" => "100",
     "1421856000000" => "110",
  );
  $newData = json_encode($data);
  echo $newData; 

This is what comes out (using the PHP code above)

{"1421852400000":"100","1421856000000":"110"}

But what I really need is the array in this format:

  [
    [1421852400000, 100], 
    [1421856000000, 110], 
    [1421859600000, 125]
  ]

Also, the first value is a timestamp (being used in Flot charts) and the second value is for the y axis of the graph.

In javascript I get these values like this:

var visit = JSON.parse(xmlhttp.responseText);       

When I simply display the desired format it works, but when I try the PHP things it's giving me some odd results..

The problem is that when I use a PHP array and encode it then echo that and fetch it with Ajax and parse it with js it's not in the right format and thus it does not work.. How would I get the desired result? Thanks in advance!

4
  • The result you want isn't JSON. Commented Jan 21, 2015 at 17:21
  • @Devon Yeah, normal array. Commented Jan 21, 2015 at 17:22
  • Oh, but how would I display it since if I just print_r an array it's displayed like: Array ( [1421852400000] => 100 [1421856000000] => 110 ) Commented Jan 21, 2015 at 17:23
  • 1
    The result he wants is JSON, but you don't understand the question. He reads the JSON in and then needs the format which is a normal array. User2879055, the problem is that you're using array keys in PHP, while the JavaScript array doesn't use keys. It's an array with arrays of length two. Commented Jan 21, 2015 at 17:27

2 Answers 2

3

This Is what you should put in the $data.

$data = array(
         array("1421852400000", "100"),
         array("1421856000000","110"), 
);

$newData = json_encode($data); 
echo $newData;

If you really need to display something similar to this:

 [
    [1421852400000, 100], 
    [1421856000000, 110], 
    [1421859600000, 125]
 ]
Sign up to request clarification or add additional context in comments.

1 Comment

Yup thanks! I was just about to post it myself since I accidentally did that when trying Amit's method. Anyways thanks it works :)
2

Change $data to something like this:

$data = array(
    array(1421852400000, 100),
    array(1421856000000, 110)
);

2 Comments

Yes, rest of code should work fine. I'm only suggesting to change format of $data.
@CamilStaps, missed it. Removed my comment. Thanks.

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.