Why doesn't this array_unique work as expected?

♀尐吖头ヾ 提交于 2019-12-23 12:23:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!