1

I have the following array of arrays in JS:

var data = [
  ['Year', 'Sales'],
  ['2014', 1000],
  ['2015', 1170],
];

How to build this array in PHP that after use in JS. I tried:

$data[] = [2014 => 1000];

echo json_encode($data);

I dont know what I do wring, I get this:

enter image description here

And it is not reproduced in Google Map Bar.

Default array:

var data = google.visualization.arrayToDataTable([
                ['Year', 'Sales'],
                ['2014', 1000],
                ['2015', 1170]
            ]);

Insted this array I put own:

var data = google.visualization.arrayToDataTable(model);

2 Answers 2

4

Like this:

$data = [
    ['Year', 'Sales'],
    ['2014', 1000],
    ['2015', 1170],
];

echo json_encode($data);

You want a multi-dimensional array, not an associative array.

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

Comments

3

=> syntax is for creating associative arrays, which are analogous to Javascript objects. But your JS is a 2D array, not an object. The PHP is:

$data = array(
    array('Year', 'Sales'),
    array('2014', 1000),
    array('2015', 1170)
);

The syntax for adding a new row to the array would be:

$data[] = array('2014', 1000);

4 Comments

Or I can us this? $data[] = [(string)$this->xLabel, (string)$this->yLabel];?
@OPV Yes, that would work as well. But you may not need to cast them to strings.
@OPV In your JS the second element is a number, not a string.
Edited question

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.