如果重复,如何删除多维数组。 在这个示例中,条形码是重复值111我想要删除它,如果发现重复。 PLease帮助我新的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
)
)
答案 0 :(得分:1)
快速解决您的问题:
<?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);
答案 1 :(得分:1)
这会跟踪每个条形码数组项的键以查找重复项,然后在末尾使用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
)
)