CodeIgniter 用户指南 版本 2.2.6

编辑文档、查看近期更改请 登录注册  找回密码
查看原文

数组辅助函数

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

装载本辅助函数

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

$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 $_POST array 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 字段被发送以进行更新。

 

翻译贡献者: canglan, Hex, zhaosusen
最后修改: 2012-02-05 23:45:13