Array 輔助函數
Array 輔助函數提供一些輔助陣列操作的相關函數。
載入輔助函數
輔助函數使用下列方式載入:
$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()
讓你從陣列中取回多個指定的元素。給定一個陣列,其中存放欲取得的陣列索引,此函式將檢查是否每個陣列索引都存在。 回傳值是一個含有你指定索引的陣列及其值,若有不存在的索引,則其值將設定為預設值FALSE。亦可透過第三個參數來指定其預設值。範例如下:
$array = array(
'color' => 'red',
'shape' => 'round',
'radius' => '10',
'diameter' => '20'
);
$my_shape = elements(array('color', 'shape', 'height'), $array);
以上程式將回傳下面的陣列:
array(
'color' => 'red',
'shape' => 'round',
'height' => FALSE
);
你可以由第三個參數設定預設值,當索引不存在時會套用預設值:
$my_shape = elements(array('color', 'shape', 'height'), $array, NULL);
以上程式將回傳下面的陣列:
array(
'color' => 'red',
'shape' => 'round',
'height' => NULL
);
當你想要將$_POST陣列傳送給Model時,這將會很有用。它可以避免傳送多餘的資料給你的Model:
$this->load->model('post_model');
$this->post_model->update(elements(array('id', 'title', 'content'), $_POST));
這可以確保僅有id,title及content的值會被送出及更新。