【问题标题】:Remove duplicate using array_unique使用 array_unique 删除重复项
【发布时间】:2015-02-10 12:21:36
【问题描述】:

您好,我正在尝试使用 wordpress 遍历标签列表。标签列表是通过另一个插件生成的。

目前这是我的代码

    <?php foreach($entities as $entity): ?>
    <?php $str = str_replace(' ', '-', esc_attr($entity->galdesc)) ?>
    <li><a href="#" id="<?php echo $str ?>"><?php echo_safe_html(nl2br($entity->galdesc)); ?></a></li>
    <?php endforeach ?>

这样输出标签列表如下

    tag1
    tag1
    tag2
    tag1
    tag3

所有标签都会这样,但我正在尝试删除重复项,我已经研究过使用 array_unique 但无法使其正常工作。

谢谢

【问题讨论】:

标签: php foreach array-unique


【解决方案1】:

你需要缓存你已经使用过的 $entity->galdesc 的值。 in_array 的方法可能如下所示:

<?php $tagnamesUsed = array(); ?>
<?php foreach($entities as $entity): ?>
<?php $str = str_replace(' ', '-', esc_attr($entity->galdesc)) ?>
<?php if (!in_array($entity->galdesc, $tagnamesUsed)): ?>
<li><a href="#" id="<?php echo $str ?>"><?php echo_safe_html(nl2br($entity->galdesc)); ?></a></li>
<?php $tagnamesUsed[] = $entity->galdesc; ?>
<?php endif; ?>
<?php endforeach ?>

【讨论】:

    【解决方案2】:

    您的数组包含对象。 array_unique() 尝试将您的数组值作为字符串进行比较。有关详细信息,请参阅此处的最佳答案:array_unique for objects?

    解决这个问题的一种方法是创建一个已经输出的标签数组,然后每次都检查它:

    <?php $arrTags = array(); ?>
    <?php foreach($entities as $entity): ?>
       <?php $str = str_replace(' ', '-', esc_attr($entity->galdesc)) ?>
    
       <?php if(in_array($str,$arrTags)){ continue; } else { $arrTags[] = $str; } ?>
    
       <li><a href="#" id="<?php echo $str ?>"><?php echo_safe_html(nl2br($entity->galdesc)); ?></a></li>
    <?php endforeach; ?>
    

    【讨论】:

      【解决方案3】:

      尝试对实体数组进行两次迭代,这并不花哨,但可能会奏效。

      1. 解析标签标题并将其添加到临时数组中
      2. 在临时数组中应用 array_unique
      3. 迭代临时数组以打印结果

      它的代码是这样的:

      <?php
      
      $tmp = array();
      foreach($entities as $entity) {
          $tmp[] = str_replace(' ', '-', esc_attr($entity->galdesc));
      }
      
      $uniques = array_unique($tmp);
      foreach ($uniques as $entity) {
          echo $entity . '<br>';
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-30
        • 2018-05-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多