คู่มือการใช้งาน CodeIgniter เวอร์ชั่น 1.7.2


Array Helper

ไฟล์ Array Helper มีฟังก์ชันที่ใช้ทำงานกับข้อมูลซึ่งเป็นอาเรย์

เรียกใช้งานผู้ช่วยนี้

ผู้ช่วยนี้จะถูกเรียกใช้งานได้จากโค้ดต่อไปนี้

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

ต่อไปจะกล่าวถึงฟังชั่นที่มีให้ใช้งาน

element()

ใช้อ่านค่าที่อยู่ใน array ออกมา ฟังชั่นนี้ใช้ได้ต้องเป็น array ที่มี index และมีค่าอยู่ในตัวแปร ซึ่งหากในตัวแปรมีค่าอยู่จะคืนค่านั้นออกมา หากไม่มีจะคืนค่าเป้น FALSE หรือสามารถกำหนดค่าเริ่มต้นได้ในพารามิเตอร์ตำแหน่งที่ 3 ตัวอย่างดังนี้

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

// คือค่า "red"
echo element('color', $array);

// คือค่าว่างเปล่า (NULL)
echo element('size', $array, NULL);

random_element()

ปรับเปลื่ยน array ที่ได้รับมาจาก input และคืนค่าซึ่งซุ่มออกมาจาก array นั้น ตัวอย่างการใช้งาน

$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);