PHP 删除重复的数组值
PHP remove duplicate array values
让我解释一下我的情况,
我给自己一个多维数组..
下面是我数组的 print_r
。
Array
(
[0] => Array
(
[firstname] => Tinga
[lastname] =>
[email] => private@information.nl
[country_code] => NL
[group] => B2B
[order_count] => 321
)
[1] => Array
(
[firstname] => Tinga
[lastname] =>
[email] => private@information.nl
[country_code] => NL
[group] => B2B
[order_count] => 12
)
[2] => Array
(
[firstname] => Rijsbergen Automotive B.V.
[lastname] =>
[email] => private@information1.nl
[country_code] => NL
[group] => B2B
[order_count] => 311
)
[3] => Array
(
[firstname] => Mike Verhoef
[lastname] => Artis Garage Amsterdam
[email] => private@information2.nl
[country_code] => NL
[group] => B2B
[order_count] => 260
)
[4] => Array
(
[firstname] => Marc Kraak
[lastname] => Vakgarage TEMA
[email] => private@information3.nl
[country_code] => NL
[group] => B2B
[order_count] => 257
)
[5] => Array
(
[firstname] => J&B Auto's
[lastname] =>
[email] => private@information4.nl
[country_code] => NL
[group] => B2B
[order_count] => 249
)
)
如你所见,有一个重复的数组,只有order_count
不同。
我可以使用 array_unique
轻松删除重复项,但随后它会随机删除其中一个数组(我相信)。
我想要的是删除基于电子邮件 (private_information) 的重复项,其中 order_count
的数量最少。 (所以只保留最高的order_count
)
有人可以帮我吗?
基于提供的数组的解决方案是:
$filtered = [];
foreach ($array as $item) {
$email = $item['email'];
if (empty($filtered[$email]) || $filtered[$email]['order_count'] < $item['order_count']) {
$filtered[$email] = $item;
}
}
让我解释一下我的情况,
我给自己一个多维数组..
下面是我数组的 print_r
。
Array
(
[0] => Array
(
[firstname] => Tinga
[lastname] =>
[email] => private@information.nl
[country_code] => NL
[group] => B2B
[order_count] => 321
)
[1] => Array
(
[firstname] => Tinga
[lastname] =>
[email] => private@information.nl
[country_code] => NL
[group] => B2B
[order_count] => 12
)
[2] => Array
(
[firstname] => Rijsbergen Automotive B.V.
[lastname] =>
[email] => private@information1.nl
[country_code] => NL
[group] => B2B
[order_count] => 311
)
[3] => Array
(
[firstname] => Mike Verhoef
[lastname] => Artis Garage Amsterdam
[email] => private@information2.nl
[country_code] => NL
[group] => B2B
[order_count] => 260
)
[4] => Array
(
[firstname] => Marc Kraak
[lastname] => Vakgarage TEMA
[email] => private@information3.nl
[country_code] => NL
[group] => B2B
[order_count] => 257
)
[5] => Array
(
[firstname] => J&B Auto's
[lastname] =>
[email] => private@information4.nl
[country_code] => NL
[group] => B2B
[order_count] => 249
)
)
如你所见,有一个重复的数组,只有order_count
不同。
我可以使用 array_unique
轻松删除重复项,但随后它会随机删除其中一个数组(我相信)。
我想要的是删除基于电子邮件 (private_information) 的重复项,其中 order_count
的数量最少。 (所以只保留最高的order_count
)
有人可以帮我吗?
基于提供的数组的解决方案是:
$filtered = [];
foreach ($array as $item) {
$email = $item['email'];
if (empty($filtered[$email]) || $filtered[$email]['order_count'] < $item['order_count']) {
$filtered[$email] = $item;
}
}