Home  >  Article  >  php教程  >  php中如何合并数组中相同的元素

php中如何合并数组中相同的元素

PHPz
PHPzOriginal
2016-06-13 11:53:351381browse

这篇文章主要介绍了php合并数组中相同元素的方法,通过一个自定义函数遍历数组实现数组中相同项的合并,是非常实用的技巧,需要的朋友可以参考下

关于重复数组的删除我们都介绍过N种方法了,今天这个例子有点不同就是 删除数组中相同的元素,只保留一个相同元素,具体实例代码如下:

代码如下:

<?php
// 删除数组中相同元素,只保留一个相同元素
function formatArray($array)
{
sort($array);
$tem = "";
$temarray = array();
$j = 0;
for($i=0;$i<count($array);$i++)
{
if($array[$i]!=$tem)
{
$temarray[$j] = $array[$i];
$j++;
}
$tem = $array[$i];
}
return $temarray;
}
//测试 调用函数
$array = array(&#39;aa&#39;,&#39;bb&#39;,&#39;aa&#39;,3,4,5,5,5,5,&#39;bc&#39;);
$arr = formatArray($array);
print_r($arr);
?>

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

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