我有两个数组,一个包含人名,另一个包含人名。
$firstname = array ( "John", "Tom", "Ben", "John", "David", "Julie", "David");
$lastname = array ( "Kennedy", "Hyde", "Hughes", "Harper" "Walter", "Weber", "Walter");
人名和姓在两个阵列中都有相同的索引(John Kennedy,Tom Hyde等)我正在寻找一种在数组$firstname
中找到重复值的方法是两个约翰和两个戴维斯,但是如果它们也是重复的话,我需要用相同的索引检查$lastname
,因此输出将是David Harper, David Harper
。
该数组可包含大约50多个不同的名称和姓氏。
在互联网上找不到任何内容,而且我的想法已经用完,任何帮助都将不胜感激。
答案 0 :(得分:3)
您必须创建一个处理结果值的第三个数组,即全名。以下示例将返回两个数组,duplicates数组和fullnames数组,没有重复:
<?php
$firstname = array ( "John", "Tom", "Ben", "John", "David", "Julie", "David");
$lastname = array ("Kennedy", "Hyde", "Hughes", "Harper", "Walter", "Weber", "Walter");
$fullname = array();
$duplicates = array();
// foreach time we have a first name.
for ($i =0; $i < count($firstname); $i++){
$fullname_tmp = $firstname[$i]." ".$lastname[$i];
if (in_array($fullname_tmp, $fullname)){
if (in_array($fullname_tmp, $duplicates)){
$duplicates[] = $fullname_tmp;
}
else{
$duplicates[] = $fullname_tmp;
$duplicates[] = $fullname_tmp;
}
}
else{
$fullname[] = $fullname_tmp;
}
}
echo "<pre>\n duplicates \n";
print_r($duplicates);
echo "\n full names \n";
print_r($fullname);
示例使用in_array
和简单的for
循环。
结帐DEMO
答案 1 :(得分:0)
简单的array_unique会解决你的问题吗?
$firstname = array ( "John", "Tom", "Ben", "John", "David", "Julie", "David");
$lastname = array ( "Kennedy", "Hyde", "Hughes", "Harper", "Walter", "Weber", "Walter");
var_dump(array_unique($firstname));
var_dump(array_unique($lastname));
输出将是
array (size=5)
0 => string 'John' (length=4)
1 => string 'Tom' (length=3)
2 => string 'Ben' (length=3)
4 => string 'David' (length=5)
5 => string 'Julie' (length=5)
array (size=6)
0 => string 'Kennedy' (length=7)
1 => string 'Hyde' (length=4)
2 => string 'Hughes' (length=6)
3 => string 'Harper' (length=6)
4 => string 'Walter' (length=6)
5 => string 'Weber' (length=5)