0

I need to store values into a Wordpress database and the use the value in a Google Chart.

The questions are: 1. What format do I use to store it into the database? Currently I am using WP-TYPES and adding the array as follows to a Multi Line Box:

['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]

This is what it needs to output in the Javascript for the chart.

  1. Convert the String to a array in PHP (Not doing it correctly) I retrieve the data with:

$graphdata = types_render_field("graph-data", array("output" => "raw","separator"=>";"));

This gives me a string value.

Then I add it to an array: $thechartcontent[$i] = [ "name" => get_the_title(), "chartheaders" => array($graphdata), ];

  1. In JavaScipt: I set the PHP Array to Java

    var chart1 = <?php echo json_encode($thechartcontent[0]); ?>;

Then I get the data from the array to a var:

 var chartheaders1 = chart1['chartheaders'];

This is where I get stuck. The value that I get is a string. It needs to show exactly this:

['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540] 

for it to work.

Any help please.

2
  • Did you try in JSON format? Commented Apr 17, 2014 at 7:45
  • I have yes. Tried json_decode, explode and serialize Commented Apr 17, 2014 at 7:53

2 Answers 2

0

Well, it will not be exacly like you want since it's JSON encoded in JSON format. This might be useful. Or you can convert object into array in JS.

2
  • How can I get it exactly like that though. Otherwise the charts don't work. Should I store it in a different format maybe? Commented Apr 17, 2014 at 7:58
  • If you don't want to change format to force json_encode to encode as array, try converting Object to Array in JS. For example with jQuery.makeArray() Commented Apr 17, 2014 at 8:21
0

I suspect that what you are outputting is an array containing a string, which is not what you want. You must split $graphdata into an array of arrays containing your data before adding it to $thechartcontent:

$graphdata = substr($graphdata, 1, strlen($graphdata) - 1); // trim the opening and closing brackets
$graphdata = explode('],[', $graphdata); // split $graphdata into an array of strings
foreach($graphdata as &$row) {
    $row = explode(',', $row); // split the row into an array
}
$thechartcontent[$i] = array(
    'name' => get_the_title(),
    'chartheaders' => $graphdata
);

When you json encode the data, you should use the JSON_NUMERIC_CHECK constant, so your numbers don't get quoted as strings:

var chart1 = <?php echo json_encode($thechartcontent[0], JSON_NUMERIC_CHECK); ?>;

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.