【发布时间】:2014-04-12 16:37:57
【问题描述】:
现在,我有一种方法可以将两个关联数组的关联数组与删除的重复值合并。代码如下:
//$mergedProp will output the final merged arrays
$mergedProp = array(array());
$prop1 = Array (
[1] => Array ( [property_code] => CODE-01 [street] => 100 Fake Street
[city] => Las Vegas [state] => NV [zip] => (no results)
[county] => (no results) [id] => 6 )
[2] => Array ( [property_code] => CODE-02 [street] => 200 Fake St
[city] => Fake City [state] => AR [zip] => 45532
[county] => Union [id] => 3 ) ) ;
$prop2 = Array (
[1] => Array ( [property_code] => CODE-03 [street] => 1140 Fake Street
[city] => Detroit [state] => MI [zip] => 45224
[county] => Hamilton [id] => 3 )
[2] => Array ( [property_code] => CODE-02 [street] => 200 Fake St
[city] => Fake City [state] => AR [zip] => 45532
[county] => Union [id] => 12 ) )
$arrayMerged = array_merge($prop1, $prop2);
$arrayUnique = array();
foreach ($arrayMerged as $row) {
$code = $row['property_code'];
if (!isset($arrayUnique[$code])) {
$arrayUnique[$code] = array();
}
$arrayUnique[$code] = array_merge($arrayUnique[$code], $row);
}
//Sorts the array
ksort($arrayUnique);
$i = 1;
$newGrid = array();
foreach($arrayUnique as $r)
$newGrid[$i++] = $r;
$countDuplicates = count($arrayMerged) - count($newGrid);
$mergedProp = $newGrid;
上面的输出:
Array (
[1] => Array ([property_code] => CODE-01 [street] => 100 Fake Street
[city] => Las Vegas [state] => NV [zip] => (no results)
[county] => (no results) [id] => 6 )
[2] => Array ([property_code] => CODE-03 [street] => 1140 Fake Street
[city] => Detroit [state] => MI [zip] => 45224
[county] => Hamilton [id] => 3 )
[3] => Array ([property_code] => CODE-02 [street] => 200 Fake St
[city] => Fake City [state] => AR [zip] => 45532
[county] => Union [id] => 12 ) )
我希望预期的输出低于:
Array (
[1] => Array ([property_code] => CODE-01 [street] => 100 Fake Street
[city] => Las Vegas [state] => NV [zip] => (no results)
[county] => (no results) [id] => 6 )
[2] => Array ([[property_code] => CODE-02 [street] => 200 Fake St
[city] => Fake City [state] => AR [zip] => 45532
[county] => Union [id] => 3 )
[3] => Array ([property_code] => CODE-03 [street] => 1140 Fake Street
[city] => Detroit [state] => MI [zip] => 45224
[county] => Hamilton [id] => 3 )
[4] => Array ([property_code] => CODE-02 [street] => 200 Fake St
[city] => Fake City [state] => AR [zip] => 45532
[county] => Union [id] => 12 ) )
我怎样才能让它保留重复的值呢?我基本上希望输出在 1 个数组中包含 $prop1 和 $prop2。
【问题讨论】:
-
不确定你的意思,当你做
$arrayMerged = array_merge($prop1, $prop2);时你已经知道了。 -
显示预期的输出。
-
@AbraCadaver 我回去并包含了预期的输出
标签: php arrays multidimensional-array