zoukankan      html  css  js  c++  java
  • 【PHP框架CodeIgniter学习】使用辅助函数—建立自己的JSONHelper

    本文使用的是2.1.4版本,看的时候请注意。

    官方文档:http://codeigniter.org.cn/user_guide/general/helpers.html(关于辅助函数Helper的使用)

    一、辅助函数是什么

            辅助函数,顾名思义,是帮助我们完成特定任务的函数。每个辅助函数文件仅仅是一些函数的集合。例如,URL Helpers 可以帮助我们创建链接,Form Helpers 可以帮助我们创建表单,Text Helpers 提供一系列的格式化输出方式,Cookie Helpers 能帮助我们设置和读取COOKIE, File Helpers能帮助我们处理文件,等等。

    二、怎么新建辅助函数

    打开applicationhelpers目录,新建json_helper.php;

    因为PHP自带的json_encode 对中文的封装不是很好,会出现u5c3cu739b这种诡异的想象,那么我们想要的目的是输出中文,所以就写一个辅助函数来自己调用;

    内容:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <?php
    function mJson_encode($jsonArray)
    {
        $newArray array();
        // encode
        for($i = 0;$i count($jsonArray);$i++)
        {
            $jsonObject $jsonArray[$i];
     
            foreach($jsonObject as $key => $value)
            {
                $newObject[$key] = urlencode ($value);
            }
            array_push($newArray $newObject);
        }
        // decode
        return urldecode (json_encode ($newArray));
    }
    ?>

    三、如何调用新建的辅助函数;

    在需要调用的controller里面,加载json_helper辅助函数,$this->load->helper(‘json’);
    然后按照正常调用PHP自带函数的方式调用即可。

    如:

    $rs = mJson_encode($data['result']);

    完整测试代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <?php
    class UserController extends CI_Controller
    {
        public function __construct()
        {
            parent::__construct();
            $this->load->helper('json');
            $this->output->set_content_type('application/html;charset=utf-8');
        }
        function index()
        {
            $this->load->model('user_model');
            $data['result'] = $this->user_model->get_last_ten_entries();
            $data['title'] = 'Hello World Page Title';
            $this->load->view('user_view'$data);
        }
        function toJson()
        {
            $this->load->model('user_model');
            $data['result'] = $this->user_model->get_last_ten_entries();
            $data['title'] = 'Hello World Page Title';
            $rs = mJson_encode($data['result']);
            echo $rs;
        }
     
    }
     
    ?>

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    js常用工具函数
    vue-cli跨域问题解决
    charles抓包404问题(左侧不显示配置)
    vuex存储与本地储存(localstorage、sessionstorage)的区别(笔记)
    借助axios的拦截器实现Vue.js中登陆状态校验的思路(笔记)
    cornerstone使用注意点
    本地仓库连接远程仓库,git本地新建项目上传到远程git仓库上正确流程
    做一个不那么差的程序员
    解决 php Call to undefined function shm_attach()
    Redis 常用的数据结构
  • 原文地址:https://www.cnblogs.com/kenshinobiy/p/4724580.html
Copyright © 2011-2022 走看看