WP63
  • Web Development
  • WordPress Development
  • Plugins
  • WP63
  • Shortnotes

array_map() ใน PHP

Published January 20, 2021

array_map() ใน PHP
Share this:
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on LINE (Opens in new window)

array_map() เป็นฟังก์ชันที่เอาไว้รับอาเรย์เข้าไป เอามาประมวลผล value ของอาเรย์ แล้วคืนค่ากลับออกมาเป็นอาเรย์ตัวใหม่ โดยค่า index หรือ key ของอาเรย์นั้นจะคงเดิมเหมือนกับในอาเรย์ต้นฉบับ

อากิวเมนต์ตัวแรกของฟังก์ชันจะเป็น callback function ส่วนตัวถัดไปจะเป็นอาเรย์ที่ต้องการจะเอามาประมวลผล

<?php
// กรณี indexed array
$numbers = [1, 2, 3, 4, 5, 6];

$multiplied = array_map( function( $number ) {
  return $number * 2;
}, $numbers );

print_r( $multiplied ); // ได้ผลลัพธ์เป็น [2, 4, 6, 8, 10, 12];

// กรณี associative array
$fruits = [
  'banana' => 1,
  'orange' => 5,
  'apple' => 3,
];

$restocked = array_map( function( $fruit ) {
  return $fruit + 5;
}, $fruits );

print_r( $restocked );
/*
ผลลัพธ์:
[
  'banana' => 6,
  'orange' => 10,
  'apple' => 8,
]
*/

ท่าที่ผมเอามาใช้ประจำคือเอามาประมวลผล WP_Query::posts ออกมาเป็นก้อนข้อมูล ก่อนที่จะส่งไปให้เท็มเพลตใช้งาน เช่น

<?php
$movies_data = new WP_Query( [
  'post_type' => 'movies',
] );

$movies = array_map( function( $movie ) {
  return [
    'title' => $movie->post_title,
    'genre' => get_field( 'genre', $movie->ID ),
  ];
}, $movies_data );

print_r( $movies );
/*
ผลลัพธ์:
[
  [
    'title' => 'Pandorum',
    'genre' => 'Sci-fi',
  ],
  [
    'title' => 'Pearl Harbor',
    'genre' => 'Action',
  ],
]
*/

ข้อดีของการใช้ array_map() คือมันจะทำให้โค้ดเราสะอาดขึ้น ช่วยลดความสับสนเวลาเขียนโค้ด และเป็นการล็อคตัวแปรให้อยู่แค่ในสโคปของ closure function ไม่ต้องกลัวว่าจะเผลอไปเปลี่ยนค่าตัวแปรนอกฟังก์ชัน

ปกติแล้วเวลาจะลูปประมวลผลตัวแปร เรามักจะใช้ foreach กัน ซึ่งมันมีปัญหาขาประจำอย่างหนึ่งคือเผลอเอาตัวแปรเก่ามาใช้แล้วลืมรีเซ็ตค่า (ซึ่งการรีเซ็ตค่าก็ต้องประกาศตัวแปรเปล่าๆ หนึ่งบรรทัดเพิ่มเข้ามาให้โค้ดรกเล่นๆ) เช่น

<?php
// บรรทัดที่ 10
$source = [ ... something ... ];

foreach ( $data => $value ) {
  $data[] = doSomething( $value );
}

// บรรทัดที่ 120 ลืมไปแล้วว่าเคยใช้ $data แล้วลืมรีเซ็ตตัวแปร
$source = [ ... another thing ... ];

foreach ( $data => $value ) {
  $data[] = doAnother( $value ); // ผลลัพธ์ไปรวมกับ $data ที่เคยใช้ก่อนหน้านี้
}

// บรรทัด 150 รีเซ็ต $data ให่้สักหน่อย
$source = [ ... everything ... ];
$data = [];

foreach ( $data => $value ) {
  $data[] = doEverything( $value );
}

อาจจะดูเล็กน้อย แต่ผมบอกว่าเลยเรื่องหลงๆ ลืมๆ แบบนี้ สร้างบั๊กตัวโตมาหลายรอบแล้ว

และหากเราใช้ PHP 7.4 ในหลายกรณีเราสามารถทำให้โค้ดสะอาดและอ่านง่ายได้ขึ้นอีกนิดหน่อยด้วยการใช้ arrow function เช่นจากตัวอย่างข้างบน เราเขียนส่วน array_map() ใหม่ได้แบบนี้

$movies = array_map( fn( $movie ) => [
  'title' => $movie->post_title,
  'genre' => get_field( 'genre', $movie->ID ),
], $movies_data );

ทั้งนี้มีข้อควรระวังอยู่เหมือนกัน คือในกรณีที่มีข้อมูลจำนวนมาก (เช่นสักล้านตัว) array_map() จะกินใช้เวลาในการประมวลผลกว่าการใช้ foreach เพราะมันมี overhead ที่เกิดจากการเรียกใช้ callback function เพิ่มเข้ามา

Share this:
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on LINE (Opens in new window)

บทความอื่นๆ ที่น่าสนใจ

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2022 WP63

  • หน้าแรก
  • ติดต่อเรา
  • นโยบายความเป็นส่วนตัว
  • ข้อตกลงการใช้งาน
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
  • Web Development
  • WordPress Development
  • Plugins

Like us

Like us

Categories

  • Blog
  • Gutenberg
  • Plugins
  • Shortnotes
  • Snippets
  • Web Development
  • WordPress Development

Popular Posts

  • ส่งอีเมลด้วย SendGrid
    ส่งอีเมลด้วย SendGrid
  • array_map() ใน PHP
    array_map() ใน PHP
  • กำหนด URL structure ได้ตามใจด้วย AltoRouter
    กำหนด URL structure ได้ตามใจด้วย AltoRouter
  • การใช้ @media print ในการกำหนด CSS สำหรับพิมพ์และ PDF
    การใช้ @media print ในการกำหนด CSS สำหรับพิมพ์และ PDF
  • การทำ Routing ใน PHP ด้วย AltoRouter
    การทำ Routing ใน PHP ด้วย AltoRouter
  • ทำเว็บให้รองรับ Dark mode ของระบบปฏิบัติการ
    ทำเว็บให้รองรับ Dark mode ของระบบปฏิบัติการ

Archives

  • April 2022
  • January 2021
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • December 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019
  • June 2019
  • March 2019
  • February 2019
  • December 2018
  • September 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • January 2018