duanjianxi8439 2014-08-11 15:33
浏览 512

从foreach循环中删除重复项

I'm trying to loop through a custom post type and display all meta values for a meta key.

I'm able to display all the values, however there are some duplicates. I want to remove those duplicates.

I have tried using array_unique without luck.

My code:

<?php
query_posts(array(
'post_type' => 'lejlighed'

 ));
 ?>
               <?php
while (have_posts()):
the_post();


$meta = get_post_meta($post->ID, 'antal_varelser');

foreach ($meta as $m) {

    echo '<option value="1">' . $m . '</option>';

}
endwhile;
?> 

The result: 2 2 3 4 3 3 4

My code with array_unique:

<?php
$the_query = new WP_Query(array(
'post_type' => 'lejlighed',
 ));
 ?>
 <?php

 while ($the_query->have_posts()):
 $the_query->the_post();
 $meta = get_post_meta($post->ID, 'antal_varelser');
 $result = array_unique($meta);

 foreach($result as $r)
 {
 echo '<option value="1">' . $m . '</option>';
 }

 endwhile; ?>

Outputs nothing.

print_r($meta) returns:

Array ( [0] => 2 ) Array ( [0] => 12 ) Array ( [0] => 4 ) Array ( [0] => 2 ) Array ( [0] => 5 ) Array ( [0] => 2 ) Array ( [0] => 4 ) Array ( [0] => 4 ) Array ( [0] => 3 ) Array ( [0] => 3 ) 

Any suggestions?

  • 写回答

3条回答 默认 最新

  • dongqishou7471 2014-08-11 15:36
    关注

    You could try to use a loop and fill another array first with:

    bool in_array ( $needle , array $haystack)
    

    Then you should have only unique values in the new array, which can be used for ur loop


    Edit:

    For me two ways are working...

    We assume this array is given:

    $org = array('1', '2', '2', '3', '3', '4', '5', '6');
    

    Simple array_unique:

    // simple array unique call with sort by string
    $new = array_unique($org, SORT_STRING);
    
    // output the sorted array
    var_dump($new);
    

    Sort array in loop by using in_array:

    // sort with in_array()
    for ($i=0; $i < count($org); $i++) {
    
        if (!in_array($org[$i], $new)) {
            $new[] = $org[$i];
        }
    }
    
    // output the sorted array
    var_dump($new);
    

    Live Demo

    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line