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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决