數(shù)組輔助函數(shù)
數(shù)組輔助函數(shù)的文件涵蓋了一些用于輔助數(shù)組操作的函數(shù)。
裝載本輔助函數(shù)
本輔助函數(shù)的裝載通過(guò)如下代碼完成:
$this->load->helper('array');
可用的函數(shù)如下:
element()
獲取數(shù)組中的元素。本函數(shù)測(cè)試數(shù)組的索引是否已設(shè)定并含有數(shù)值。如果已設(shè)有數(shù)值則返回該數(shù)值,否則返回 FALSE,或任何你設(shè)定的默認(rèn)數(shù)值(函數(shù)第三個(gè)參數(shù))。范例:
$array = array('color' => 'red', 'shape' => 'round', 'size' => '');
// 返回 "red"
echo element('color', $array);
// 返回 NULL
echo element('size', $array, NULL);
random_element()
根據(jù)提供的數(shù)組,隨機(jī)返回該數(shù)組內(nèi)的一個(gè)元素。使用范例:
$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:
試譯:該函數(shù)從一個(gè)數(shù)組中取得若干元素。該函數(shù)測(cè)試(傳入)數(shù)組的每個(gè)鍵值是否在(目標(biāo))數(shù)組中已定義;如果一個(gè)鍵值不存在,該鍵值所對(duì)應(yīng)的值將被置為FALSE,或者你可以通過(guò)傳入的第3個(gè)參數(shù)來(lái)指定默認(rèn)的值。例如:
$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:
試譯:上面的程序?qū)⒎祷叵旅娴臄?shù)組:
array(
????'color' => 'red',
????'shape' => 'round',
????'height' => FALSE
);
You can set the third parameter to any default value you like:
試譯:你可以將第3個(gè)參數(shù)設(shè)為任何你想要的默認(rèn)值:
$my_shape = elements(array('color', 'shape', 'height'), $array, NULL);
The above will return the following array:
試譯:上面的程序?qū)⒎祷叵旅娴臄?shù)組:
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 數(shù)組傳入你的模型時(shí)非常有用。通過(guò)這種方式可以防止用戶(hù)發(fā)送的額外的 POST 數(shù)據(jù)進(jìn)入你的數(shù)據(jù)表:
$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 字段被發(fā)送以進(jìn)行更新。
?