dongyou26216708 2016-05-23 21:57
浏览 81
已采纳

从PHP创建JavaScript数组 - 方括号和花括号

I am trying to pass code from my PHP backend to the google-chart JavaScript API. I have had success using PHP’s json_encode(), for passing arrays of numbers and strings. For simple data arrays json_encode() works just fine:

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

But, the Google Charts API requires that row-parameters be passed as objects in {curly braces}.

Here is the JavaScript array I am trying to produce:

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, '']
];

The trouble is producing the {role: 'annotation'} bit in PHP. Any suggestions?

  • 写回答

2条回答 默认 最新

  • doudui2229 2016-05-23 22:01
    关注

    This should do the trick:

    $data = [['Series1', 'Series2', ['role'=>'annotation']], [0, 1], [2, 3], [3, 4]]; 
    

    You can create objects in php by creating a new stdClass, but an dictionary (key => value array) is converted to JSON the same way (with curly brackets). This would work as well:

    $object = new stdClass();
    $object->role = 'annotation';
    
    $data = [['Series1', 'Series2', $object], [0, 1], [2, 3], [3, 4]];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?