dongpigui8898 2013-06-20 16:09
浏览 34
已采纳

javascript图中使用的PHP数组数据 - codeigniter

I am using API data in a model which is passed through to a controller then to view. In one particular instance I need to do a foreach() loop but in javascript to get the data I need, please see below how I've done it.

I know this is bad practice but wanted to know what the best practice is to achieve this so I know going forward.

categories: [<?php foreach($champ_name as $champ_id => $stat_value) {
               foreach ($stat_value as $cn => $cs) {
                   if($champ_id != 0) {
                       echo '"'.$cn.'",';
                   }
               } 
            } ?>]

Thanks for looking/helping.

(PS. the above does work but I know is not the right way)

  • 写回答

1条回答

  • dongyishe6689 2013-06-20 16:14
    关注

    You can use json_encode() to convert it into an object or array that Javascript can use.

    categories: <?php echo json_encode($myThing); ?>
    

    For your use, you would still need your foreach logic to build an array to be json encoded.

    If you build the array manually like in your question, you need to be mindful over special characters from breaking the array and causing syntax errors. For example if any of your $cn contained a double quote, it would produce a syntax error. The benefit of json encoding it is that any special characters will be taken care of without you having to handle them.

    Example:

    $arr = array('abc', 3, 'te"xt', 6);
    echo json_encode($arr);
    

    Outputs

    ["abc",3,"te\"xt",6]
                ^ qoute has been automatically escaped
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败