數(shù)組輔助函數(shù)
數(shù)組輔助函數(shù)的文件涵蓋了一些用于輔助數(shù)組操作的函數(shù)。
裝載本輔助函數(shù)
本輔助函數(shù)的裝載通過如下代碼完成:
$this->load->helper('array');
可用的函數(shù)如下:
element()
獲取數(shù)組中的元素。本函數(shù)測試數(shù)組的索引是否已設定并含有數(shù)值。如果已設有數(shù)值則返回該數(shù)值,否則返回 FALSE,或任何你設定的默認數(shù)值(函數(shù)第三個參數(shù))。范例:
$array = array('color' => 'red', 'shape' => 'round', 'size' => '');
// 返回 "red"
echo element('color', $array);
// 返回 NULL
echo element('size', $array, NULL);
random_element()
根據(jù)提供的數(shù)組,隨機返回該數(shù)組內(nèi)的一個元素。使用范例:
$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ù)從一個數(shù)組中取得若干元素。該函數(shù)測試(傳入)數(shù)組的每個鍵值是否在(目標)數(shù)組中已定義;如果一個鍵值不存在,該鍵值所對應的值將被置為FALSE,或者你可以通過傳入的第3個參數(shù)來指定默認的值。例如:
$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個參數(shù)設為任何你想要的默認值:
$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ù)組傳入你的模型時非常有用。通過這種方式可以防止用戶發(fā)送的額外的 POST 數(shù)據(jù)進入你的數(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ā)送以進行更新。
?