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

Home php教程 php手冊(cè) PHP關(guān)聯(lián)數(shù)組的10個(gè)操作技巧

PHP關(guān)聯(lián)數(shù)組的10個(gè)操作技巧

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

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

復(fù)制代碼 代碼如下:


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


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

復(fù)制代碼 代碼如下:


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


5、編輯數(shù)組值
假設(shè)在數(shù)組中的數(shù)據(jù)包含大小寫錯(cuò)誤,在插入到數(shù)據(jù)庫(kù)之前,你想糾正這些錯(cuò)誤,你可以使用array_map()函數(shù)給每個(gè)數(shù)組元素應(yīng)用一個(gè)回調(diào)。

復(fù)制代碼 代碼如下:


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


6、按鍵對(duì)數(shù)組排序
FlashCard程序常常使用各種排序,如按字母順序排序,你可以使用ksort()函數(shù)按鍵對(duì)關(guān)聯(lián)數(shù)組進(jìn)行排序。

復(fù)制代碼 代碼如下:


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


因?yàn)閿?shù)組是通過(guò)參數(shù)傳遞給ksort()函數(shù)的,意味著你不再需要將排序結(jié)果分配給另一個(gè)變量。
7、隨機(jī)數(shù)組排序
在FlashCard程序中還涉及到另一種隨機(jī)排序技術(shù),這時(shí)你要使用shuffle()函數(shù)實(shí)現(xiàn)數(shù)組項(xiàng)目的隨機(jī)排序。

復(fù)制代碼 代碼如下:


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


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

復(fù)制代碼 代碼如下:


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


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

復(fù)制代碼 代碼如下:


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


9、搜索數(shù)組
你可能想搜索數(shù)組資源,這樣用戶就可以方便地用一個(gè)特定的州府檢索關(guān)聯(lián)的州,可以通過(guò)array_search()函數(shù)實(shí)現(xiàn)數(shù)組搜索。

復(fù)制代碼 代碼如下:


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


10、標(biāo)準(zhǔn)PHP庫(kù)
標(biāo)準(zhǔn)PHP庫(kù)(Standard PHP Library,SPL)為開(kāi)發(fā)人員提供了許多數(shù)據(jù)結(jié)構(gòu),迭代器,接口,異常和其它以前PHP語(yǔ)言沒(méi)有的功能,使用這些功能可以通過(guò)面向?qū)ο蟮恼Z(yǔ)法遍歷數(shù)組。

復(fù)制代碼 代碼如下:


$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眾多偉大功能中的一個(gè),一定要閱讀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