本文使用的是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
|
<?phpfunction 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
|
<?phpclass 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;
}
}?> |
版权声明:本文为博主原创文章,未经博主允许不得转载。