频道栏目
首页 > 资讯 > CI框架 > 正文

CI 框架怎样操作数组? CI框架操作数组的技巧谈。数组辅助函数

16-01-07        来源:[db:作者]  
收藏   我要投稿
转载CI框架的一个例子,跟你是说明数组的一些技巧,CI PHP 来自CI中国

数组辅助函数的文件涵盖了一些用于辅助数组操作的函数。

装载本辅助函数

本辅助函数的装载通过如下代码完成:

$this->load->helper('array');

可用的函数如下:

element()

获取数组中的元素。本函数测试数组的索引是否已设定并含有数值。如果已设有数值则返回该数值,否则返回 FALSE,或任何你设定的默认数值(函数第三个参数)。范例:

$array = array('color' => 'red', 'shape' => 'round', 'size' => '');

// 返回 "red"
echo element('color', $array);

// 返回 NULL
echo element('size', $array, NULL);

random_element()

根据提供的数组,随机返回该数组内的一个元素。使用范例:

$quotes = array(
"I find that the harder I work, the more luck I seem to have. - Thomas Jefferson",
"Don't stay in bed, unless you can make money in bed. - George Burns",
"We didn't lose the game; we just ran out of time. - Vince Lombardi",
"If everything seems under control, you're not going fast enough. - Mario Andretti",
"Reality is merely an illusion, albeit a very persistent one. - Albert Einstein",
"Chance favors the prepared mind - Louis Pasteur"
);

echo random_element($quotes);

elements()

Lets you fetch a number of items from an array. The function tests whether each of the array indices is set. If an index does not exist it is set to FALSE, or whatever you’ve specified as the default value via the third parameter. Example:

试译:该函数从一个数组中取得若干元素。该函数测试(传入)数组的每个键值是否在(目标)数组中已定义;如果一个键值不存在,该键值所对应的值将被置为FALSE,或者你可以通过传入的第3个参数来指定默认的值。例如:

$array = array(
'color' => 'red',
'shape' => 'round',
'radius' => '10',
'diameter' => '20'
);

$my_shape = elements(array('color', 'shape', 'height'), $array);

The above will return the following array:

试译:上面的程序将返回下面的数组:

array(
'color' => 'red',
'shape' => 'round',
'height' => FALSE
);

You can set the third parameter to any default value you like:

试译:你可以将第3个参数设为任何你想要的默认值:

$my_shape = elements(array('color', 'shape', 'height'), $array, NULL);

The above will return the following array:

试译:上面的程序将返回下面的数组:

array(
'color' => 'red',
'shape' => 'round',
'height' => NULL
);

This is useful when sending the$_POSTarray to one of your Models. This prevents users from sending additional POST data to be entered into your tables:

试译:这(种方法)在将$_POST数组传入你的模型时非常有用。通过这种方式可以防止用户发送的额外的 POST 数据进入你的数据表:

$this->load->model('post_model');

$this->post_model->update(elements(array('id', 'title', 'content'), $_POST));

This ensures that only the id, title and content fields are sent to be updated.

试译:这样保证了只有 id, title 和 content 字段被发送以进行更新。

相关TAG标签
上一篇:php模板引擎smarty变量类型
下一篇:Yaf零基础学习总结5-Yaf类的自动加载
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站