php 数组过滤函数 array_filter与array_unique
在php中我给大家介绍两个比较常用的数组过滤函数array_filter与array_unique了,一个是过滤数组空值,一个是过滤数组重复值,我们现在一起来看看。
语法
array_filter(array,function)
参数 描述
array 必需。规定输入的数组。
function 自定义函数的名称,为空时过滤掉所有值为flase的元素
<?php function odd($var) { return ($var & 1); } function even($var) { return (!($var & 1)); } $array1 = array( "a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5 ); $array2 = array( 6, 7, 8, 9, 10, 11, 12 ); echo "Odd :n"; print_r(array_filter($array1, "odd")); echo "Even:n"; print_r(array_filter($array2, "even")); /* Odd : Array ( [a] => 1 [c] => 3 [e] => 5 ) Even: Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12 ) */ ?>
过滤掉PHP数组中的重复值
去除一个数组中的重复值,可以使用foreach方法,也可以使用array_unique方法,下面的代码两种方法都使用了
<?php $arrF = array(); $arrS = array(); $intTotal = 100; $intRand = 10; for ($i = 0; $i < $intTotal; $i++) { $arrF[] = rand(1, $intRand); $arrS[] = rand(1, $intRand); } $arrT = array_merge($arrF, $arrS); $arrRF = array(); $intStart = time(); foreach ($arrT as $v) { if (in_array($v, $arrRF)) { continue; } else { $arrRF[] = $v; } } $intEnd = time(); $intTime = $intEnd - $intStart; echo "With Continue,Spend time:$intTime<br/>"; $intStart1 = time(); $arrRS = array_unique($arrT); $intEnd2 = time(); $intTime2 = $intEnd2 - $intStart1; echo "With array_unique function,Spend time:($intTime2)"; echo "<pre class="brush:php;toolbar:false">"; print_r($arrT); print_r($arrRF); print_r($arrRS); echo "
在$intTotal比较小的情况下,比如说1000以内,$intRand的取值基本不影响结果,两者执行的时间都差不多。
测试$intTotal 大于10000时,$intRand取值100时,使用array_unique的效率要高于foreach循环判断,$intRand=10,两者执行时间一致。
因此,可以得出结论,当数组容量不大,大概在1000以内时,使用两者的执行效率差不多。
当数组容量比较大时(具体应该到什么值,我没有详细测试,感兴趣的可以确定一下这个值),随着$intRand的逐渐增大,array_unique的表现更好,我不使用$intTotal/$intRand这个比值,是因为,感觉并不是成比例变化,但是基本会遵循比值越大,array_unique表现越好。
综上所述,在过滤数组重复值的时候,建议使用array_unuique,数组不大的时候两者效率等同,而array_unique使用当然让你的代码一下子减了好几行,数组容量过大时,函数的表现更好
二维数组去重复项函数
PHP数组去除重复项 有个内置函数array_unique (),但是php的 array_unique函数只适用于一维数组,对多维数组并不适用,以下提供一个二维数组 的 array_unique函数
<?php function unique_arr($array2D, $stkeep = false, $ndformat = true) { // 判断是否保留一级数组键 (一级数组键可以为非数字) if ($stkeep) $stArr = array_keys($array2D); // 判断是否保留二级数组键 (所有二级数组键必须相同) if ($ndformat) $ndArr = array_keys(end($array2D)); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串 foreach ($array2D as $v) { $v = join(",", $v); $temp[] = $v; } //去掉重复的字符串,也就是重复的一维数组 $temp = array_unique($temp); //再将拆开的数组重新组装 foreach ($temp as $k => $v) { if ($stkeep) $k = $stArr[$k]; if ($ndformat) { $tempArr = explode(",", $v); foreach ($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval; } else $output[$k] = explode(",", $v); } return $output; } ?>
测试
$array2D = array('first'=>array('title'=>'1111','date'=>'2222'),'second'=>array('title'=>'1111','date'=>'2222'),'third'=>array('title'=>'2222','date'=>'3333')); print_r($array2D); print_r(unique_arr($array2D,true));

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



1. The difference between Iterator and foreach is the polymorphic difference (the bottom layer of foreach is Iterator) Iterator is an interface type, it does not care about the type of collection or array; both for and foreach need to know the type of collection first, even the type of elements in the collection; 1. Why is it said that the bottom layer of foreach is the code written by Iterator: Decompiled code: 2. The difference between remove in foreach and iterator. First, look at the Alibaba Java Development Manual, but no error will be reported in case 1, and an error will be reported in case 2 (java. util.ConcurrentModificationException) first

The steps for PHP to determine the number of the foreach loop: 1. Create an array of "$fruits"; 2. Create a counter variable "$counter" with an initial value of 0; 3. Use "foreach" to loop through the array, and Increase the value of the counter variable in the loop body, and then output each element and their index; 4. Output the value of the counter variable outside the "foreach" loop to confirm which element the loop reaches.

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values swapped. $original_array=[

The explode function in PHP is a function used to split a string into an array. It is very common and flexible. In the process of using the explode function, we often encounter some errors and problems. This article will introduce the basic usage of the explode function and provide some methods to solve the error reports. 1. Basic usage of the explode function In PHP, the basic syntax of the explode function is as follows: explode(string$separator,string$stri

Title: Common errors and solutions when using the explode function in PHP In PHP, the explode function is a common function used to split a string into an array. However, some common errors can occur due to improper use or incorrect data format. This article will analyze the problems you may encounter when using the explode function, and provide solutions and specific code examples. Mistake 1: The delimiter parameter is not passed in. When using the explode function, one of the most common mistakes is that the delimiter parameter is not passed in.

In PHP programming, processing strings is a frequently required operation. Among them, splitting and merging strings are two common requirements. In order to perform these operations more conveniently, PHP provides two very practical functions, namely the explode and implode functions. This article will introduce the usage of these two functions, as well as some practical skills. 1. The explode function The explode function is used to split a string according to the specified delimiter and return an array. Its function prototype is as follows: arra

This article will explain in detail about the current element in the array returned by PHP. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. Get the current element in a PHP array PHP provides a variety of methods for accessing and manipulating arrays, including getting the current element in an array. The following introduces several commonly used techniques: 1. current() function The current() function returns the element currently pointed to by the internal pointer of the array. The pointer initially points to the first element of the array. Use the following syntax: $currentElement=current($array);2.key() function key() function returns the array internal pointer currently pointing to the element

Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, but forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. The execution efficiency of for is higher than forEach.
