大家都应该掌握的PHP关联数组使用技巧,
大家都应该掌握的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<br />", $state, $capital); } // The capital of Arizona is Phoenix // The capital of Alaska is Juneau // The capital of Alabama is Montgomery
以上就是10个必须掌握的PHP关联数组使用技巧,希望对大家的学习有所帮助。
您可能感兴趣的文章:
- PHP关联数组的10个操作技巧
- PHP和JavaScrip分别获取关联数组的键值示例代码
- php中怎么搜索相关联数组键值及获取之
- PHP将两个关联数组合并函数提高函数效率
- php通过asort()给关联数组按照值排序的方法
- php通过array_merge()函数合并关联和非关联数组的方法
- PHP中把对象转换为关联数组代码分享
- php关联数组快速排序的方法
- PHP关联数组实现根据元素值删除元素的方法

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
