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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据