简体   繁体   中英

How to convert multidimensional array from PHP to JavaScript?

I try a little with dygraph. I get my data from an ajax call and I need to convert my returned JSON array to a JavaScript array.

Now my dygraph options look like this

    series = {
      sample1: {
        color: 'Green',
        strokeWidth: 3,
        pointSize: 4
      },
      sample2: {
        color: 'DarkBlue',
        strokeWidth: 2,
        pointSize: 3
      },
      sample3: {
        color: 'DarkOrange',
        strokeWidth: 1,
        pointSize: 2
      }
    }

   dygraph_options = {
      title: title,
      labels: jsonDataTable.labels,
      series: series,
      ...
   }

My php ajax call look like this:

$series = array();
$series[] = array( 'sample1' => array('color' => 'Green'));
$series[] = array( 'sample2' => array('color' => 'DarkBlue'));
$series[] = array( 'sample3' => array('color' => 'DarkOrange'));

$table = array( "series" => $series, "labels" => $labels, "data" => $rows );
return $table;

I want to get the series from json. But my returned series are different from the javascript series:

jsonDataTable.series -> [Object { stock={...}}, Object { forecast={...}}]
javascript series -> Object { stock={...}, forecast={...}, training={...}}

I try a lot but can't get it working.

You want $series to be an associative array:

$series = array();
$series['sample1'] = array('color' => 'Green');
$series['sample2'] = array('color' => 'DarkBlue');
$series['sample3'] = array('color' => 'DarkOrange');

Or

$series = array(
   'sample1' => array('color' => 'Green'),
   'sample2' => array('color' => 'DarkBlue'),
   'sample3' => array('color' => 'DarkOrange')
);

Prepare array to send from php to javascript:

echo json_encode( $array );

Translate the data in javascript to a nice object

var a = JSON.parse( phpdata );

Prep to send data to php from javascript

var tosend = JSON.stringify( a );

Translate incoming js object back into php

$a = json_decode( $some_json );

or

$a = json_decode( $some_json, true );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM