如何删除重复的多维数组。在这个例子中,条形码是111的重复值,如果发现重复,我想删除它。PLease help我是php新手。感谢
输出:
Array
(
[0] => Array
(
[Barcode] => 111
[Transaction_No] => 256
)
[1] => Array
(
[Barcode] => 111
[Transaction_No] => 0
)
[2] => Array
(
[Barcode] => 222
[Transaction_No] => 0
)
)
预期输出:
Array
(
[0] => Array
(
[Barcode] => 222
[Transaction_No] => 0
)
)
这会跟踪每个条形码数组项的键以查找重复项,然后在末尾使用array_values来修复数组索引。
<?php
$myArray = array(
array
(
"Barcode" => 111,
"Transaction_No" => 256
),
array
(
"Barcode" => 111,
"Transaction_No" => 0
),
array
(
"Barcode" => 222,
"Transaction_No" => 0
)
);
$barcodeKeys = array();
foreach ($myArray as $key => $arr) {
$code = $arr["Barcode"];
if (!isset($barcodeKeys[$code])) {
$barcodeKeys[$code] = array();
}
$barcodeKeys[$code][] = $key;
if (count($barcodeKeys[$code]) > 1) {
foreach ($barcodeKeys[$code] as $dupKey) {
if (isset($myArray[$dupKey])) {
unset($myArray[$dupKey]);
}
}
}
}
$myArray = array_values($myArray);
print_r($myArray);
输出
Array
(
[0] => Array
(
[Barcode] => 222
[Transaction_No] => 0
)
)
快速解决问题的方法:
<?php
$barcodes = array(array( 'Barcode' => 111,'Transaction_No' => 256),array('Barcode' => 111,'Transaction_No' => 0),array('Barcode' => 222,'Transaction_No' => 0),array('Barcode' => 333,'Transaction_No' => 0));
$result = array();
$exist = array();
foreach($barcodes as $key => $item){
if( in_array( $item['Barcode'], array_values( $exixt ) ){
unset( $result[ array_search ( $item['Barcode'], $exist ) ] );
} else {
$result[ $key ] = array('Barcode' => $item['Barcode'],'Transaction_No' => $item['Transaction_No'] );
$exist[ $item['Barcode'] ] = $key;
}
}
var_dump($result);