dqrzot2791 2018-01-24 11:00
浏览 51
已采纳

如何将php数组格式化为javascript数组?

I have a 3D array in php when using var_dump($arr) it looks like this

array(2) { 
[0]=> array(4) { 
  [0]=> array(2) { [0]=> string(7) "36.3636" [1]=> int(8) } 
  [1]=> array(2) { [0]=> string(7) "27.2727" [1]=> int(5) } 
  [2]=> array(2) { [0]=> string(7) "36.3636" [1]=> int(2) } 
  [3]=> array(2) { [0]=> string(7) "28.5714" [1]=> int(10) } 
} 

[1]=> array(3) { 
   [0]=> array(2) { [0]=> string(7) "18.1818" [1]=> int(10) } 
   [1]=> array(2) { [0]=> string(7) "18.1818" [1]=> int(9) } 
   [2]=> array(2) { [0]=> string(6) "0.0000" [1]=> int(6) } 
} 


} 

I want to get it in this format in javascript:

var data = [
                [
                  {x:36, y:8, r:10},{x:27, y:5, r:10},{x:36, y:2, r:10},{x:28, y:10, r:10}
                ],
                [
                  {x:18, y:10, r:10},{x:18, y:9, r:10},{x:0, y:6, r:10}
                ]
            ];

Where x is the [0] index of innermost array and y is [1] index of innermost array r is always 10

How do i format it in this way ?

  • 写回答

3条回答 默认 最新

  • dongxiangxie8181 2018-01-24 11:12
    关注

    You could format the data then echo the result as a javascript variable.

    <?php
    
    $data = [
      [
        [ "36.3636", 8 ],
        [ "27.2727", 5 ],
        [ "36.3636", 2 ],
        [ "28.5714", 10 ],
      ],
      [
        [ "18.1818", 10 ],
        [ "18.1818", 9 ],
        [ "0.0000", 6 ],
      ]
    ];
    
    // reformat the data in php to your desired format
    $formatted = array_map(function($coords) {
      return array_map(function($item) {
        return [
          'x' => (int) $item[0],
          'y' => (int) $item[1],
          'r' => 10,
        ];
      }, $coords);
    }, $data);
    
    ?>
    <!-- echo json encode your formatted data as a javascript variable -->
    <script>var data = <?=json_encode($formatted, JSON_NUMERIC_CHECK)?>;</script>
    <script>console.log(data)</script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?