search
HomeBackend DevelopmentPHP TutorialBest way to deduplicate arrays and keep key names in PHP
Best way to deduplicate arrays and keep key names in PHPMay 01, 2024 pm 01:00 PM
Array deduplicationform submissionKeep key name

There are two best ways to deduplicate arrays and keep key names in PHP: array_unique(): It can deduplicate but not retain key names and re-index the array. Custom function array_unique_preserve_keys(): Use hash values ​​to compare values, which can remove duplicates and preserve key names.

PHP 中对数组去重并保持键名的最佳方法

The best way to deduplicate arrays and keep key names in PHP

In PHP, array deduplication means Remove duplicate values ​​while keeping key names unchanged. This is useful when working with data from different sources that may contain duplicate elements, such as from multiple form submissions or database queries.

Method 1: array_unique()

The array_unique() function is a built-in PHP function used to deduplicate arrays. It accepts an array as input and returns a new array in which duplicate values ​​have been removed. However, array_unique() does not preserve key names, but re-indexes the array, starting at 0.

Example:

$arr = ['a', 'b', 'c', 'c', 'd', 'e', 'a'];

$result = array_unique($arr);

print_r($result); // 输出:['a', 'b', 'c', 'd', 'e']

Method 2: Custom function

To keep the key name, we can write a custom function to deduplicate an array. This method uses an associative array and compares the hash of each value to determine if it is a duplicate.

Example:

function array_unique_preserve_keys($arr)
{
    $hash = [];
    $unique_arr = [];

    foreach ($arr as $key => $value)
    {
        $hash_value = md5($value);
        if (!isset($hash[$hash_value]))
        {
            $hash[$hash_value] = 1;
            $unique_arr[$key] = $value;
        }
    }

    return $unique_arr;
}

$arr = ['a', 'b', 'c', 'c', 'd', 'e', 'a'];

$result = array_unique_preserve_keys($arr);

print_r($result); // 输出:['a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd', 'e' => 'e']

Practical case:

Suppose we have an array from a form submission that contains duplicates Username and email address. By deduplicating it using the array_unique_preserve_keys() function, we can remove duplicate records while maintaining the user's username.

$form_data = [
    ['username' => 'john', 'email' => 'john@example.com'],
    ['username' => 'jane', 'email' => 'jane@example.com'],
    ['username' => 'john', 'email' => 'john@example.org'],
    ['username' => 'mark', 'email' => 'mark@example.net']
];

$unique_users = array_unique_preserve_keys($form_data);

print_r($unique_users); // 输出:['john' => ['username' => 'john', 'email' => 'john@example.com'], 'jane' => ['username' => 'jane', 'email' => 'jane@example.com'], 'mark' => ['username' => 'mark', 'email' => 'mark@example.net']]

The above is the detailed content of Best way to deduplicate arrays and keep key names in PHP. For more information, please follow other related articles on the PHP Chinese website!

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
PHP 数组去重时指定去除重复元素的依据PHP 数组去重时指定去除重复元素的依据Apr 28, 2024 pm 10:48 PM

PHP的array_unique()函数用于去除数组中重复元素,其缺省使用严格相等(===)。我们可以通过自定比较函数来指定去重依据:创建自定比较函数,指定去重的标准(例如根据元素长度);将自定比较函数作为第三个参数传递给array_unique()函数,即可根据指定的标准去除重复元素。

es5和es6怎么实现数组去重es5和es6怎么实现数组去重Jan 16, 2023 pm 05:09 PM

es5中可以利用for语句和indexOf()函数来实现数组去重,语法“for(i=0;i<数组长度;i++){a=newArr.indexOf(arr[i]);if(a==-1){...}}”。在es6中可以利用扩展运算符、Array.from()和Set来去重;需要先将数组转为Set对象来去重,然后利用扩展运算符或Array.from()函数来将Set对象转回数组即可。

哪些JS事件不会向上冒泡?哪些JS事件不会向上冒泡?Feb 19, 2024 pm 09:56 PM

JS事件中有哪些不会冒泡的情况?事件冒泡(EventBubbling)是指在触发了某个元素的事件后,事件会从最内层元素开始沿着DOM树向上传递,直到最外层的元素,这种传递方式称为事件冒泡。但是,并不是所有的事件都能冒泡,有一些特殊情况下事件是不会冒泡的。本文将介绍在JavaScript中有哪些情况下事件不会冒泡。一、使用stopPropagati

Vue中如何实现表单的校验和提交Vue中如何实现表单的校验和提交Oct 15, 2023 am 11:14 AM

Vue中如何实现表单的校验和提交在Web开发中,表单是用户与网页进行交互的重要界面,表单中用户输入的数据需要进行校验和提交,以确保数据的合法性和完整性。Vue.js是一个流行的前端框架,它提供了便捷的表单校验和提交方法,使我们能够快速地实现表单功能。本文将介绍如何使用Vue.js来实现表单的校验和提交,并提供具体的代码示例。一、表单校验安装vee-valid

PHP 数组去重后如何保持键值对应?PHP 数组去重后如何保持键值对应?Apr 27, 2024 pm 12:33 PM

PHP数组去重后保持键值对应的方法有:使用array_unique()函数去除重复值,再用array_flip()函数交换键值对。将原始数组与去重后的数组合并,使用数组合并的方法来保留键值对应。

Vue中的v-on指令解析:如何处理表单提交事件Vue中的v-on指令解析:如何处理表单提交事件Sep 15, 2023 am 09:12 AM

Vue中的v-on指令解析:如何处理表单提交事件在Vue.js中,v-on指令用于绑定事件监听器,可以捕获并处理各种DOM事件。其中,处理表单提交事件是Vue中常见的操作之一。本文将介绍如何使用v-on指令处理表单提交事件,并提供具体的代码示例。首先,需要明确Vue中的表单提交事件指的是当用户点击submit按钮或按下回车键时触发的事件。在Vue中,可以通过

如何利用Vue表单处理实现表单提交前的数据预处理如何利用Vue表单处理实现表单提交前的数据预处理Aug 10, 2023 am 09:21 AM

如何利用Vue表单处理实现表单提交前的数据预处理概述:在Web开发中,表单是平常最常见的元素之一。而在表单提交前,我们经常需要对用户输入的数据进行一些预处理,例如格式校验、数据转换等。Vue框架提供了方便易用的表单处理功能,本文将介绍如何利用Vue表单处理实现表单提交前的数据预处理。一、创建Vue实例和表单控件首先,我们需要创建一个Vue实例并定义一个包含表

常见的jQuery事件列表常见的jQuery事件列表Feb 24, 2024 am 11:57 AM

【jQuery中常用的事件一览,需要具体代码示例】jQuery是一个流行的JavaScript库,广泛用于网页开发中。在jQuery中,事件处理是一个非常重要的部分,通过事件我们可以实现页面的交互和动态效果。本文将介绍jQuery中常用的事件,包括点击事件、鼠标事件、键盘事件等,并提供具体的代码示例。一、点击事件1.click事件click事件是元素被点击

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools