我有一个这样的数组
$non_unique_zip
[0]->[0]91390
[1]ca
[2]1
[1]->[0]91391
[1]ca
[2]1
[2]->[0]91392
[1]ca
[2]1
[3]->[0]91390
[1]ca
[2]2
[4]->[0]91394
[1]ca
[2]2
所以基本上数组有元素,其中arra[n][0]是zipcode和数组[n][2]是buyer_id。现在,我只想要有多个买家的邮政编码。所以我唯一想提取的是
[0]->[0]91390
[1]ca
,因为91390是唯一的邮政编码,其中买方为1和2。我试着
$result = array();
$first = $non_unique_zip[0];
for($i=0; $i<count($non_unique_zip); $i++){
$result = array_intersect ($first, $non_unique_zip[$i]);
$first = $result;
}
但是它只是给出了错误未定义的偏移量。
如果您将$records
称为您的起始数组,那么这里有一种方法可以使用3行代码获得zip:
//array whose keys are zips, and values are # of occurances
$zips = array_count_values(array_column($records,0));
//filter keeps only zips which occur more than once.
$zips = array_filter($zips,function($n){return $n>1;});
//if you only need the zips, you're done! they are the keys
$zips = array_keys($zips);
现场演示
使用一个数组来跟踪以前已经遇到的邮政编码。然后当你得到那个数组中的zip文件时,你就知道它是重复的。
$zips = array();
$result = array();
foreach ($non_unique_zip as $e) {
$code = $e[0];
if (isset($zips[$code])) { // duplicate, so add to $result
$result[$code] = array($code, $e[1]);
} else {
$zips[$code] = true; // first time, add it to $zips
}
}
像这样使用array_walk
:
<?php
$non_unique_zip = [
[91390, "ca"],
[91391, "ca"],
[91392, "ca"],
[91390, "ca"],
[91394, "ca"],
];
$unique_zip = [];
$duplicates = [];
array_walk($non_unique_zip, function($data) use(&$unique_zip, &$duplicates){
if(!in_array($data, $unique_zip)){
$unique_zip[] = $data;
}else{
$duplicates[] = $data;
}
});
var_dump( $duplicates );
// PRODUCES::
array (size=1)
0 =>
array (size=2)
0 => int 91390
1 => string 'ca' (length=2)
var_dump( $unique_zip );
// PRODUCES::
array (size=4)
0 =>
array (size=2)
0 => int 91390
1 => string 'ca' (length=2)
1 =>
array (size=2)
0 => int 91391
1 => string 'ca' (length=2)
2 =>
array (size=2)
0 => int 91392
1 => string 'ca' (length=2)
3 =>
array (size=2)
0 => int 91394
1 => string 'ca' (length=2)