我正在尝试从多维数组中删除重复值。我已经尝试了许多例子,但我没有得到我想要的。
我的阵列在这里
Array
(
[0] => Array
(
[0] => stdClass Object
(
[CouponCode] => REZEZ150
[PurchaseAmt] => 1000.00
[DiscountAmt] => 150.00
)
[1] => stdClass Object
(
[CouponCode] => REZEZ500
[PurchaseAmt] => 2500.00
[DiscountAmt] => 500.00
)
)
[1] => Array
(
[0] => stdClass Object
(
[CouponCode] => REZEZ150
[PurchaseAmt] => 1000.00
[DiscountAmt] => 150.00
)
[1] => stdClass Object
(
[CouponCode] => REZEZ350
[PurchaseAmt] => 2000.00
[DiscountAmt] => 350.00
)
[2] => stdClass Object
(
[CouponCode] => REZEZ500
[PurchaseAmt] => 2500.00
[DiscountAmt] => 500.00
)
)
)
删除像
这样的重复值后我想要数组 Array
(
[0] => Array
(
[0] => stdClass Object
(
[CouponCode] => REZEZ150
[PurchaseAmt] => 1000.00
[DiscountAmt] => 150.00
)
[1] => stdClass Object
(
[CouponCode] => REZEZ350
[PurchaseAmt] => 2000.00
[DiscountAmt] => 350.00
)
[2] => stdClass Object
(
[CouponCode] => REZEZ500
[PurchaseAmt] => 2500.00
[DiscountAmt] => 500.00
)
)
)
类似的问题与答案,但没有解决我的情况:
[How to remove duplicates from multidimensional array in php \[duplicate\]][1]
答案 0 :(得分:0)
试试这个,
$arrResult = $arrResult1 = array();
foreach($arrData as $key1 => $arrData1){
foreach($arrData1 as $key2 => $arrData2){
$arrResult[] = $arrData2;
}
}
$arrResult1[] = array_map("unserialize", array_unique(array_map("serialize", $arrResult)));
echo "<pre>"; print_r($arrResult1);
答案 1 :(得分:0)
谢谢 我已经解决了 首先,我将其改为单维数组,如
$a = Array
(
[0] => stdClass Object
(
[CouponCode] => REZEZ150
[PurchaseAmt] => 1000.00
[DiscountAmt] => 150.00
)
[1] => stdClass Object
(
[CouponCode] => REZEZ500
[PurchaseAmt] => 2500.00
[DiscountAmt] => 500.00
)
[2] => stdClass Object
(
[CouponCode] => REZEZ150
[PurchaseAmt] => 1000.00
[DiscountAmt] => 150.00
)
[3] => stdClass Object
(
[CouponCode] => REZEZ350
[PurchaseAmt] => 2000.00
[DiscountAmt] => 350.00
)
[4] => stdClass Object
(
[CouponCode] => REZEZ500
[PurchaseAmt] => 2500.00
[DiscountAmt] => 500.00
)
)
之后运行foreach循环代表KEY AND VALUE Like
$j=array();
foreach ($a as $key => $value) {
$j[$value->CouponCode]['CouponCode']=$value->CouponCode;
$j[$value->CouponCode]['PurchaseAmt']=$value->PurchaseAmt;
$j[$value->CouponCode]['DiscountAmt']=$value->DiscountAmt;
}
p($j);
现在我得到了结果
Array
(
[REZEZ150] => Array
(
[CouponCode] => REZEZ150
[PurchaseAmt] => 1000.00
[DiscountAmt] => 150.00
)
[REZEZ500] => Array
(
[CouponCode] => REZEZ500
[PurchaseAmt] => 2500.00
[DiscountAmt] => 500.00
)
[REZEZ350] => Array
(
[CouponCode] => REZEZ350
[PurchaseAmt] => 2000.00
[DiscountAmt] => 350.00
)
)
请建议我是不是好方法?
答案 2 :(得分:0)
使用array_filter()
:
$couponCodes = array();
$a = array_filter($a, function (stdClass $purchase) use (&$couponCodes) {
if (in_array($purchase->CouponCode, $couponCodes)) {
return false;
}
$couponCodes[] = $purchase->CouponCode;
return true;
});