要在Javascript中使用的PHP数组的数据库字符串值


Database string value to PHP array to be used in Javascript

我需要将值存储到Wordpress数据库中,并在Google图表中使用该值。

问题是:1.我使用什么格式将其存储到数据库中?目前,我正在使用WP-TYPES,并将阵列添加到多行框中,如下所示:

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

这就是它需要在图表的Javascript中输出的内容。

  1. 在PHP中将字符串转换为数组(操作不正确)我使用以下方式检索数据:

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

这给了我一个字符串值。

然后我将其添加到数组中:$thechartcontent[$i] = [ "name" => get_the_title(), "chartheaders" => array($graphdata), ];

  1. 在JavaScipt中:我将PHP数组设置为Java

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

然后我从数组中获取数据到var:

 var chartheaders1 = chart1['chartheaders'];

这就是我陷入困境的地方。我得到的值是一个字符串。它需要准确地显示这一点:

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

让它发挥作用。

请帮忙。

好吧,它不会像你想要的那样糟糕,因为它是用JSON格式编码的JSON。这可能很有用。或者您可以在JS中将对象转换为数组。

我怀疑您输出的是一个包含字符串的数组,而这不是您想要的。在将数据添加到$thechartcontent:之前,必须将$graphdata拆分为包含数据的数组

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

当您对数据进行json编码时,您应该使用JSON_NUMERIC_CHECK常量,这样您的数字就不会被引用为字符串:

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