开发者

Why doesn't this array_unique work as expected?

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 = expl开发者_如何学编程ode('|', $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 :|


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 />';
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜