我有一个多维数组,我从数据库中得到,我想检查这个数组的重复数据,并将其存储在另一个重复数组中。我的代码如下
//create temp array
$tmp = array();
foreach ($matchingarray as $nameKey => $match) {
// loop through and stoe the contents of that array to another so i can compare
$tmp[] = $match;
}
// create an array to store duplicates
$duplicatesArray = array();
// if the temp array is not empty then loop through both arrays
if (! empty($tmp)) {
foreach ($tmp as $key => $tmpvalue) {
foreach ($matchingarray as $key => $match) {
// if a key name is the same in both arrays then add it tothe duplicates array
if ($tmpvalue['name'] == $match['name']) {
$duplicatesArray = $match;
}
}
}
}
//count how many are duplicates
$dups = count($duplicatesArray);
我想知道的是这是正确的逻辑吗?
我将从Igoel离开的地方开始
有一个错误,我也建议我将做。
误差:您不能在foreach中重复使用$key两次,因为它们会覆盖。
建议如Igoel所说:有效复制的最佳选择是使用sql。SQL的处理速度比遍历数组要快。不要忘记需要将数据加载到内存中,这是非常昂贵的。
试试这个
<?php
static $cnt = array();
$min = 1;
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k){
global $cnt;
$cnt[] = $v;
}
array_walk_recursive($coll, 'recursive_search');
$newNumbers = array_filter(
array_count_values($cnt),
function ($value) use($min) {
return ($value > $min);
}
);
echo "Values > 1 are repeated n";
print_r(array_count_values($cnt));
echo "Values repetedn";
print_r($newNumbers);