国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊 PHP關聯數組的10個操作技巧

PHP關聯數組的10個操作技巧

Jun 13, 2016 am 11:56 AM
php What use association exist develop Skill operate array yes of conduct

什么是數組?
在使用 PHP 進行開發(fā)的過程中,或早或晚,您會需要創(chuàng)建許多相似的變量。
無需很多相似的變量,你可以把數據作為元素存儲在數組中。
數組中的元素都有自己的 ID,因此可以方便地訪問它們。
關聯數組
關聯數組,它的每個 ID 鍵都關聯一個值。
在存儲有關具體命名的值的數據時,使用數值數組不是最好的做法。
通過關聯數組,我們可以把值作為鍵,并向它們賦值。
這篇文章將介紹10個操作PHP關聯數組的技巧,熟練運用能幫助你提高開發(fā)效率。
1、添加數組元素
PHP是一種弱類型語言,這意味著你不需要顯示聲明一個數組及其大小,相反,你可以同時聲明并填充數組。
$capitals = array(
'Alabama' => 'Montgomery',
'Alaska' => 'Juneau',
'Arizona' => 'Phoenix'
); 額外的數組元素可以象下面這樣追加:
$capitals['Arkansas'] = 'Little Rock'; 如果你正在處理數字索引數組,你可能想使用顯示命名的函數前置和追加元素,如array_push()和array_unshift()函數,但這些函數不能操作關聯數組。
2、刪除數組元素
如果要從數組中刪除一個元素,請使用unset()函數,如:
unset($capitals['California']); 使用數字索引數組時,刪除數組元素的辦法更多,更靈活,可以使用array_shift()和array_pop()函數分別從數組的開頭和末尾刪除一個元素。
3、交換鍵和值
假設你想創(chuàng)建一個名叫$states的新數組,使用州府作為索引,使用州名作為關聯值,使用array_flip()函數很容易完成這個任務。

復制代碼 代碼如下:


$capitals = array(
'Alabama' => 'Montgomery',
'Alaska' => 'Juneau',
'Arizona' => 'Phoenix'
);
$states = array_flip($capitals);
// $states = array(
// 'Montgomery' => string 'Alabama',
// 'Juneau' => string 'Alaska',
// 'Phoenix' => string 'Arizona'
// );


4、合并數組
假設前面的數組由一個基于Web的“FlashCard”服務使用,你想提供一種方法測試學生對美國各州首府的掌握情況,你可以使用array_merge()函數合并包含州和首府的數組。

復制代碼 代碼如下:


$stateCapitals = array(
'Alabama' => 'Montgomery',
'Alaska' => 'Juneau',
'Arizona' => 'Phoenix'
);
$countryCapitals = array (
'Australia' => 'Canberra',
'Austria' => 'Vienna',
'Algeria' => 'Algiers'
);
$capitals = array_merge($stateCapitals, $countryCapitals);


5、編輯數組值
假設在數組中的數據包含大小寫錯誤,在插入到數據庫之前,你想糾正這些錯誤,你可以使用array_map()函數給每個數組元素應用一個回調。

復制代碼 代碼如下:


function capitalize($element)
{
$element = strtolower($element);
return ucwords($element);
}
$capitals = array(
'Alabama' => 'montGoMEry',
'Alaska' => 'Juneau',
'Arizona' => 'phoeniX'
);
$capitals = array_map("capitalize", $capitals);


6、按鍵對數組排序
FlashCard程序常常使用各種排序,如按字母順序排序,你可以使用ksort()函數按鍵對關聯數組進行排序。

復制代碼 代碼如下:


$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
ksort($capitals);


因為數組是通過參數傳遞給ksort()函數的,意味著你不再需要將排序結果分配給另一個變量。
7、隨機數組排序
在FlashCard程序中還涉及到另一種隨機排序技術,這時你要使用shuffle()函數實現數組項目的隨機排序。

復制代碼 代碼如下:


$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
shuffle($capitals);


如果不需要打亂數組順序,你只是想隨機選擇一個值,那么使用array_rand()函數即可。
8、確定鍵和值是否存在
你可以使用in_array()函數確定一個數組元素是否存在。

復制代碼 代碼如下:


$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
if (in_array("Juneau", $capitals))
{
echo "Exists!";
} else {
echo "Does not exist!";
}


很少有人知道這個函數也可以確定一個數組鍵是否存在,在這一點上,它和array_key_exists()函數的功能一樣。

復制代碼 代碼如下:


$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
if (array_key_exists("Alaska", $capitals))
{
echo "Key exists!";
} else {
echo "Key does not exist!";
}


9、搜索數組
你可能想搜索數組資源,這樣用戶就可以方便地用一個特定的州府檢索關聯的州,可以通過array_search()函數實現數組搜索。

復制代碼 代碼如下:


$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
$state = array_search('Juneau', $capitals);
// $state = 'Alaska'


10、標準PHP庫
標準PHP庫(Standard PHP Library,SPL)為開發(fā)人員提供了許多數據結構,迭代器,接口,異常和其它以前PHP語言沒有的功能,使用這些功能可以通過面向對象的語法遍歷數組。

復制代碼 代碼如下:


$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
$arrayObject = new ArrayObject($capitals);
foreach ($arrayObject as $state => $capital)
{
printf("The capital of %s is %s
", $state, $capital);
}
// The capital of Arizona is Phoenix
// The capital of Alaska is Juneau
// The capital of Alabama is Montgomery


這僅僅是SPL眾多偉大功能中的一個,一定要閱讀PHP文檔了解更多信息。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why We Comment: A PHP Guide Why We Comment: A PHP Guide Jul 15, 2025 am 02:48 AM

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

How to Install PHP on Windows How to Install PHP on Windows Jul 15, 2025 am 02:46 AM

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

PHP Syntax: The Basics PHP Syntax: The Basics Jul 15, 2025 am 02:46 AM

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

PHP 8 Installation Guide PHP 8 Installation Guide Jul 16, 2025 am 03:41 AM

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

python if else example python if else example Jul 15, 2025 am 02:55 AM

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

Your First PHP Script: A Practical Introduction Your First PHP Script: A Practical Introduction Jul 16, 2025 am 03:42 AM

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

What is PHP and What is it Used For? What is PHP and What is it Used For? Jul 16, 2025 am 03:45 AM

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

how to handle undefined index in PHP how to handle undefined index in PHP Jul 15, 2025 am 02:08 AM

The "undefinedindex" error occurs because a key that does not exist in the array is accessed. Solutions include: 1. Use isset() to check whether the key exists, which is suitable for processing user input; 2. Use array_key_exists() to determine whether the key is set, and it can be recognized even if the value is null; 3. Use the empty merge operator?? to set the default value to avoid directly accessing undefined keys; in addition, you need to pay attention to common problems such as the spelling of form field names, the database result is empty, the array unpacking is not verified, the child keys are not checked in foreach, and the session_start() is not called.

See all articles