PHP Array การค้นหาข้อมูลใน Array ด้วย in_array() และ array_intersect()

โดย SONGCHAI SAETERN
การค้นหาข้อมูลใน Array

ถ้าเรารับข้อมูลที่ส่งเข้ามาผ่าน $_POST และได้ข้อมูลตัวอย่างเก็บไว้ใน $php_func ดังนี้
<?php
$php_func = array (
  'id' => '',
  'order_date' => 'to_thai_full_month',
  'order_user_id' => '',
  'order_remark' => '',
  'order_status' => '',
);
echo "ผลลัพธ์ : " , in_array('to_thai_full_month', $php_func).'<br/>';
?>
เมื่อต้องการค้นหาว่ามีการส่งค่า to_thai_full_month มาด้วยหรือไม่เราสามารถใช้ฟังก์ชั่น in_array() ค้นหาข้อมูลในตัวแปร เมื่อพบจะได้ผลลัพธ์ดังนี้



แต่ถ้าเกิดว่า เราต้องการค้นหาหลายค่า การจะวนลูปด้วย foreach() แล้วตรวจทีละค่าก็ได้ หรือเราจะใช้ array_intersect() ที่เป็นฟังก์ชั่นของ PHP ที่มีมาให้อยู่แล้วก็ย่อมสะดวกรวดเร็วกว่า

<?php
$php_func = array (
  'id' => '',
  'order_date' => 'to_thai_full_month',
  'order_user_id' => '',
  'order_remark' => '',
  'order_status' => '',
);
$date_key = array('to_thai_full_month', 'to_thai_short_month', 'to_thai_date');
$has_date_func = array_intersect($php_func, $date_key);
if ( !empty($has_date_func) ) {
    echo "<b>ผลลัพธ์ :</b><br/>";
    foreach($has_date_func as $field=>$func){
        echo "<br>$field => $func";
    }
}
?>

เมื่อดูผลลัพธ์ ก็จะได้ข้อมูลออกมาเป็นอาร์เรย์สามารถนำไปใช้ทันที



ฟังก์ชั่นที่เกี่ยวข้อง

in_array()
array_intersect()
empty()
foreach()


---------------------------------------------------------------------------------------------

PHP CI MANIA - PHP Code Generator 

โปรแกรมช่วยสร้างโค้ด "ลดเวลาการเขียนโปรแกรม"
 http://fastcoding.phpcodemania.com/index.php/#purchase-order
สนใจสั่งซื้อราคาสุดคุ้ม 1,500 บาท
http://fastcoding.phpcodemania.com