2016-05-23 122 views
0

我試圖從我的PHP後端代碼傳遞到Google圖表JavaScript API。我已經成功使用PHP的json_encode()來傳遞數組和字符串。 對於簡單的數據陣列json_encode()工作得很好:從PHP創建JavaScript數組 - 方括號和花括號

<?php $data = [['Series1', 'Series2'], [0, 1], [2, 3], [3, 4]]; /> 
<script> 
var data = <?php echo(json_encode($data));?>; 
</script> 

但是,在Google Charts API要求行參數爲{花括號}對象通過。

這裏是JavaScript數組我試圖產生:

var data = [ 
    ['Genre', 'Fantasy & Sci Fi', 'Romance', 'Mystery/Crime', 'General', 
    'Western', 'Literature', { role: 'annotation' } ], 
    ['2010', 10, 24, 20, 32, 18, 5, ''], 
    ['2020', 16, 22, 23, 30, 16, 9, ''], 
    ['2030', 28, 19, 29, 30, 12, 13, ''] 
]; 

麻煩的是生產在PHP中{role: 'annotation'}位。有什麼建議麼?

+0

當您在'

0

可以用PHP創建一個對象,並json_encode將創建一個對象:

$myObj = new stdClass; 
$myObj->role = "annotation"; 

然後 'json_encode($ MyObj中);'將返回你想要的JSON對象。