search
HomeBackend DevelopmentPHP TutorialPHP关联数组的10个操作技巧_PHP

什么是数组?
在使用 PHP 进行开发的过程中,或早或晚,您会需要创建许多相似的变量。
无需很多相似的变量,你可以把数据作为元素存储在数组中。
数组中的元素都有自己的 ID,因此可以方便地访问它们。
关联数组
关联数组,它的每个 ID 键都关联一个值。
在存储有关具体命名的值的数据时,使用数值数组不是最好的做法。
通过关联数组,我们可以把值作为键,并向它们赋值。
这篇文章将介绍10个操作PHP关联数组的技巧,熟练运用能帮助你提高开发效率。
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、交换键和值
假设你想创建一个名叫$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)为开发人员提供了许多数据结构,迭代器,接口,异常和其它以前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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use