我正在尝试将代码从 PHP 后端传递到 google-chart JavaScript API。我已经成功地使用 PHP 的 json_encode()
来传递数字和字符串数组。
对于简单的数据数组 json_encode()
工作得很好:
<?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'}
位。有什么建议吗?
最佳答案
这应该可以解决问题:
$data = [['Series1', 'Series2', ['role'=>'annotation']], [0, 1], [2, 3], [3, 4]];
您可以通过创建新的 stdClass
在 php 中创建对象,但字典(键 => 值数组)会以相同的方式转换为 JSON(使用大括号)。这也可以工作:
$object = new stdClass();
$object->role = 'annotation';
$data = [['Series1', 'Series2', $object], [0, 1], [2, 3], [3, 4]];
关于javascript - 从 PHP 创建 JavaScript 数组 – 方括号和大括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37401227/