【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能帮助我们处理文件,等等。
二、怎么新建辅助函数
打开application\helpers目录,新建json_helper.php;
因为PHP自带的json_encode 对中文的封装不是很好,会出现\u5c3c\u739b这种诡异的想象,那么我们想要的目的是输出中文,所以就写一个辅助函数来自己调用;
内容:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?phpfunctionmJson_encode($jsonArray){    $newArray= array();    // encode    for($i= 0;$i< count($jsonArray);$i++)    {        $jsonObject= $jsonArray[$i];        foreach($jsonObjectas$key=> $value)        {            $newObject[$key] = urlencode ($value);        }        array_push($newArray, $newObject);    }    // decode    returnurldecode (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 | <?phpclassUserController extendsCI_Controller{    publicfunction__construct()    {        parent::__construct();        $this->load->helper('json');        $this->output->set_content_type('application/html;charset=utf-8');    }    functionindex()    {        $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);    }    functiontoJson()    {        $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;    }}?> | 
版权声明:本文为博主原创文章,未经博主允许不得转载。
    如何联系我:【我的公司】www.xinzhenkj.com(信真科技)【技术咨询】www.laohuzx.com  【QQ】3396726884 
图书购买京东链接***微信小程序商城开发实战*** | ***新媒体营销精华:精准定位+爆款打造+匠心运营+内容变现***
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号