This article introduces the content of deleting duplicate elements of arrays in PHP. It has certain reference value. Now I share it with you. Friends in need can refer to it.
Several methods of deleting array elements in PHP are here In many cases, our arrays will be duplicated. So what should we do if we delete some duplicate contents in the array? These elements must remain unique, so we try to find a way to delete them. The following uses a traversal query to delete several duplicate array elements. method.
Method 1. Completely delete duplicate array instances-----Delete one element in the array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function array_remove_value(&$arr, $var){ foreach ($arr as $key => $value) { if (is_array($value)) { array_remove_value($arr[$key], $var); } else { $value = trim($value); if ($value == $var) { unset($arr[$key]); } else { $arr[$key] = $value; } } } } Copy after login |
##$a is an array:
##?
2 3 4 5 6 | count($a); //得到4 unset($a[1]); //删除第二个元素 count($a); //得到3 echo $a[2]; //数组中仅有三个元素,本想得到最后一个元素,但却得到blue, echo $a[1]; //无值 ?> Copy after login |
function array_splice()
in php4.
3 4 5 6
|
# #?
456789 ## function delmember(&$array, $id) { $size = count($array); for($i = 0; $i <$size - $id - 1; $i ++) { $array[$id + $i] = $array[$id + $i + 1]; } unset($array[$size - 1]); } Copy after login | 补充小例子: 方法一、php有内置函数array_unique可以用来删除数组中的重复值
注意键名保留不变。array_unique() 先将值作为字符串排序,然后对每个值只保留第一个遇到的键名,接着忽略所有后面的键名。这并不意味着在未排序的 array 中同一个值的第一个出现的键名会被保留。
上例将输出:
方法二、array_flip实现去重效果 另一个方法是使用php的array_flip函数来间接的实现去重效果
二种方法不同的是用array_flip得到的是重复元素最后的键和值,用array_unique得到的是二个重复元素第一个键和值。 希望本文所述对大家学习php程序设计有所帮助,解决数组重复元素问题。 相关推荐: The above is the detailed content of Remove duplicate elements from array in PHP. For more information, please follow other related articles on the PHP Chinese website!
Previous article:php comparison operators
Next article:A pitfall in obtaining remote images with PHP
Statement of this Website
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
Latest Articles by Author
Latest Issues
Group MySQL results by ID for looping over
I have a table with flight data in mysql. I'm writing a php code that will group and displ...
From 2024-04-06 17:27:56
0
1
406
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
|