php 數(shù)組過濾函數(shù) array_filter與array_unique
May 25, 2016 pm 04:53 PM在php中我給大家介紹兩個比較常用的數(shù)組過濾函數(shù)array_filter與array_unique了,一個是過濾數(shù)組空值,一個是過濾數(shù)組重復值,我們現(xiàn)在一起來看看。
語法
array_filter(array,function)
參數(shù) ? ? 描述
array ? ? 必需。規(guī)定輸入的數(shù)組。
function ? ? 自定義函數(shù)的名稱,為空時過濾掉所有值為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數(shù)組中的重復值
去除一個數(shù)組中的重復值,可以使用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以內(nèi),$intRand的取值基本不影響結(jié)果,兩者執(zhí)行的時間都差不多。
測試$intTotal 大于10000時,$intRand取值100時,使用array_unique的效率要高于foreach循環(huán)判斷,$intRand=10,兩者執(zhí)行時間一致。
因此,可以得出結(jié)論,當數(shù)組容量不大,大概在1000以內(nèi)時,使用兩者的執(zhí)行效率差不多。
當數(shù)組容量比較大時(具體應該到什么值,我沒有詳細測試,感興趣的可以確定一下這個值),隨著$intRand的逐漸增大,array_unique的表現(xiàn)更好,我不使用$intTotal/$intRand這個比值,是因為,感覺并不是成比例變化,但是基本會遵循比值越大,array_unique表現(xiàn)越好。
綜上所述,在過濾數(shù)組重復值的時候,建議使用array_unuique,數(shù)組不大的時候兩者效率等同,而array_unique使用當然讓你的代碼一下子減了好幾行,數(shù)組容量過大時,函數(shù)的表現(xiàn)更好
二維數(shù)組去重復項函數(shù)
PHP數(shù)組去除重復項 有個內(nèi)置函數(shù)array_unique (),但是php的 array_unique函數(shù)只適用于一維數(shù)組,對多維數(shù)組并不適用,以下提供一個二維數(shù)組 的 array_unique函數(shù)
<?php function unique_arr($array2D, $stkeep = false, $ndformat = true) { // 判斷是否保留一級數(shù)組鍵 (一級數(shù)組鍵可以為非數(shù)字) if ($stkeep) $stArr = array_keys($array2D); // 判斷是否保留二級數(shù)組鍵 (所有二級數(shù)組鍵必須相同) if ($ndformat) $ndArr = array_keys(end($array2D)); //降維,也可以用implode,將一維數(shù)組轉(zhuǎn)換為用逗號連接的字符串 foreach ($array2D as $v) { $v = join(",", $v); $temp[] = $v; } //去掉重復的字符串,也就是重復的一維數(shù)組 $temp = array_unique($temp); //再將拆開的數(shù)組重新組裝 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

Undress AI Tool
Undress images for free

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

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

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

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.

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.

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

Use the PHP function "explode" to split a string into an array. In PHP development, you often encounter situations where you need to split a string according to the specified delimiter. At this time, we can use PHP's built-in function "explode" to convert string to array. This article will introduce how to use the "explode" function to split a string and give relevant code examples. The basic syntax of the "explode" function is as follows: arrayexplode(
