dqz86173 2015-05-13 11:49
浏览 46
已采纳

从MYSQL输出中排序数组并省略重复值

My query returns from my database rows of data containing arrays of years. For example:

1 > 2004,2005,2006,2007 
2 > 2003,2004,2005 
3 > 2004,2005,2006,2007.

When I select this data I combine it into an array then use array_unique to filter out the duplicates, however this does not work. I am returned with a complete array containing all values.

mysql_query('select * from stock where Make LIKE "%'.$_REQUEST['Make'].'%" AND Model LIKE "%'.$_REQUEST['model'].'%" group by YearRange order by YearRange DESC');

while($row=mysql_fetch_array($Year)){
    $a = explode(',', $row['YearRange']);
    $unique_array = array_unique($a);
    foreach ($unique_array as $key => $value)
    {
        echo "<option>".$value."</option>";
    }
}

So in the above example where I would only want the following values to show: 2003,2004,2005,2006,2007 in each <option>

I get:

2004,2005,2006,2007,2003,2004,2005,2004,2005,2006,2007 in each <option>

  • 写回答

1条回答 默认 最新

  • douzhangwei5265 2015-05-13 12:39
    关注

    There are a couple of ways to attack the problem. In my example I show a pretty verbose way, with two foreach() loops -

    while($row=mysql_fetch_array($Year)){
        $a = explode(',', $row['YearRange']);
        foreach($a as $year){
            $allYears[] = $year; // each row contributes to one large array
        }
    }
    
    // now work with $allYears
    $unique = array_unique($allYears);
    sort($unique);
    
    // generate your output
    foreach ($unique as $key => $value){
       echo "<option>".$value."</option>";
    }
    

    Part of the problem in your original code is that you're overwriting your unique array each time instead of creating one array ($allYears in this case), then getting the unique values from that one array. Your foreach() in the while loop is echoing out the unique values from the row and then moving to the next row to echo out the next set of values. Moving the output outside of the while loop allows you to gather all of the data, manipulate it, then perform the output of unique values.

    In addition, please stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO, it's not as hard as you think.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM