POV
POV

Reputation: 12015

Build array in PHP like to JS?

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);

Upvotes: 1

Views: 73

Answers (2)

Barmar
Barmar

Reputation: 781878

=> 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);

Upvotes: 3

Ethan
Ethan

Reputation: 4375

Like this:

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

echo json_encode($data);

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

Upvotes: 4

Related Questions