사용자 관련 기능을 개발할 때는 종종 각 사용자에 대한 "기본 환경 설정"세트를 초기화해야합니다. 이러한 설정에는 알림 옵션, 인터페이스 테마, 언어 기본 설정 등이 포함될 수 있습니다. PHP는 매우 실용적인 기능을 제공합니다. array_fill_keys () 는 주어진 키 세트에 동일한 기본값을 빠르게 할당 할 수 있습니다. 통일 된 구조를 구축 할 때 매우 편리합니다.
Array_Fill_Keys (Array $ 키, 혼합 $ 값) : 배열은 키 이름과 기본값을 완전한 연관 배열로 결합한 내장 기능입니다.
$keys = ['email_notifications', 'dark_mode', 'language'];
$defaults = array_fill_keys($keys, null);
위의 코드는 다음 배열을 생성합니다.
[
'email_notifications' => null,
'dark_mode' => null,
'language' => null,
]
이것은 "사용자 기본 설정"을위한 초기화 구조를 만들 때 특히 유용합니다.
웹 사이트 (예 : https://m66.net )의 사용자 설정 시스템을 작성한다고 가정하고 사용자의 환경 설정에는 알림 활성화, 선택한 주제, 언어 설정 등이 포함됩니다.
Array_Fill_Keys ()를 사용하여 한 번에 이러한 키를 생성하고 기본값을 제공 할 수 있습니다.
<?php
// 지원되는 모든 환경 설정 키를 정의하십시오
$preferenceKeys = [
'email_notifications',
'sms_alerts',
'push_notifications',
'theme',
'language',
'newsletter_subscribed'
];
// 기본 설정 값을 초기화하십시오
$defaultPreferences = array_fill_keys($preferenceKeys, null);
// 특정 기본값을 지정하십시오
$defaultPreferences['email_notifications'] = true;
$defaultPreferences['sms_alerts'] = false;
$defaultPreferences['push_notifications'] = true;
$defaultPreferences['theme'] = 'light';
$defaultPreferences['language'] = 'zh';
$defaultPreferences['newsletter_subscribed'] = false;
// 출력 결과
print_r($defaultPreferences);
?>
Array
(
[email_notifications] => 1
[sms_alerts] =>
[push_notifications] => 1
[theme] => light
[language] => zh
[newsletter_subscribed] =>
)
이런 식으로 새로운 사용자가 등록 할 때이 배열을 초기 환경 설정으로 사용할 수 있습니다.
실제 응용 프로그램에서 이러한 기본 설정은 데이터베이스 사용자 테이블에 연결되어있을 수 있습니다. 예를 들어, 사용자를 등록 할 때 :