问题
Can anybody tell me why this doesn't work as expected?
<?php
$merchant_string = '123-Reg|Woolovers|Roxio|Roxio|BandQ|Roxio|Roxio|Big Bathroom Shop|Roxio|Robert Dyas|Roxio|Roxio|PriceMinister UK|Cheap Suites|Kaspersky|Argos|Argos|SuperFit|PriceMinister UK|Roxio|123-Reg';
$merchant_array = explode('|', $merchant_string);
for($i = 0; $i<count($merchant_array); $i++)
{
$merchant_array = array_unique($merchant_array);
echo $merchant_array[$i] . '<br />';
}
?>
The results I get is:
Woolovers
Roxio
BandQ
Big Bathroom Shop
Robert Dyas
All I want is the duplicates gone :|
回答1:
First, you should be calling it before the loop since it only needs to be filtered once.
Second, keys are preserved when you use array_unique()
, so PHP is attempting to loop through no-longer-existent indices in your array, and may miss some out at the end as well because count($merchant_array)
now returns a smaller value. You need to reset the keys first (using array_values()
), then loop it.
$merchant_array = array_values(array_unique($merchant_array));
for($i = 0; $i<count($merchant_array); $i++)
{
echo $merchant_array[$i] . '<br />';
}
Alternatively, use a foreach loop to skip the array_values()
call:
$merchant_array = array_unique($merchant_array);
foreach ($merchant_array as $merchant) {
echo $merchant . '<br />';
}
来源:https://stackoverflow.com/questions/4241891/why-doesnt-this-array-unique-work-as-expected