PHP中关联数组的用法详解
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()函数合并包含州和首府的数组。
代码如下 | 复制代码 |
|
5、编辑数组值
假设在数组中的数据包含大小写错误,在插入到数据库之前,你想纠正这些错误,你可以使用array_map()函数给每个数组元素应用一个回调。
代码如下 | 复制代码 |
|
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()函数实现数组搜索。
代码如下 | 复制代码 |
|
10、标准PHP库
标准PHP库(Standard PHP Library,SPL)为开发人员提供了许多数据结构,迭代器,接口,异常和其它以前PHP语言没有的功能,使用这些功能可以通过面向对象的语法遍历数组。
代码如下 | 复制代码 |
|
遍历关联数组的三种方法:
foreach
代码如下 | 复制代码 |
$sports = array( 'football' => 'good', 'swimming' => 'very well', 'running' => 'not good' ); foreach ($sports as $key => $value) { echo $key.": ".$value." "; } ?> |
程序运行结果:
football: good
swimming: very well
running: not good
each
代码如下 | 复制代码 |
$sports = array( 程序运行结果: football: good |
list & each
代码如下 | 复制代码 |
$sports = array( 程序运行结果: football: good |
哈希表== Hash Table
有一份用户名列表,存储了 10000 个用户名,没有重复项;
还有一份黑名单列表,存储了 2000 个用户名,格式与用户名列表相同;
现在需要从用户名列表中删除处在黑名单里的用户名,要求用尽量快的时间处理。
这个问题是一个小规模的处理量,如果实际一点,2 个表都可能很大,比如有 2 亿条记录。
我最开始想到的方法,就是做一个嵌套的循环,设用户名表有 M 条记录,黑名单列表有 N 条记录,那么,循环的次数是 M * N 次!
PHP 版代码:
代码如下 | 复制代码 |
foreach($arrayM as $keyM => $nameM) { foreach($arrayN as $nameN) { if ($nameM == $nameN) { // 本行执行了 M * N 次! unset($arrayM[$keyM]); } } } return $arrayM; ?> |
另一种方式,利用数组索引。
PHP 是一种弱类型的语言,不像 C 语言那样有严格的变量类型限制。C 语言的数组,每一个元素的类型必须一致,而且索引都是从 0 开始。
PHP 的数组,可以用字符串作为索引,也称为关联数组。
数组索引,有一个天然的限制就是不会重复,而且访问的时候不需要查找,可以直接定位。
还是刚才的那个问题,我们采用另一种办法。
把黑名单列表的用户名组织到一个数组里,数组的索引就是用户名。
然后,遍历用户列表的时候,只需直接用 isset 查询那个用户名是否存在即可。
PHP 版代码:
代码如下 | 复制代码 |
$arrayHash = array(); foreach($arrayM as $keyM => $nameM) { |
可以看到,优化过的代码,循环次数是 M + N 次。
假如 M 和 N 都是 10000,优化前,循环了 1 亿次;优化后,只循环了 20000 次,差了 5000 倍!
如果第二个程序耗时 1 秒,则第一个程序需要将近一个半小时

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

AI Hentai Generator
Generate AI Hentai for free.

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

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible
