2014-04-17 49 views
0

我需要將值存儲到Wordpress數據庫中並使用Google Chart中的值。要在PHP中使用的數組的數據庫字符串值

問題是: 1.我用什麼格式將它存儲到數據庫中? 目前我使用WP-類型和添加陣列如下的多行框:

['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] 

它的工作。

請任何幫助。

+0

你試過用JSON格式嗎? – HeroFTime

+0

我有。嘗試json_decode,爆炸和序列化 –

回答

0

那麼,它不會像你想要的那樣無懈可擊,因爲它是以JSON格式編碼的JSON。 This might be useful。或者你可以將對象轉換爲JS中的數組。

+0

我怎樣才能得到它就像那樣。否則,圖表不起作用。我應該以不同的格式存儲它嗎? –

+0

如果您不想更改格式以強制json_encode以數組的形式進行編碼,請嘗試將對象轉換爲JS中的數組。例如使用jQuery.makeArray() –

0

我懷疑你輸出的是一個包含一個字符串的數組,這不是你想要的。你必須將它添加到$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); ?>; 
相關問題