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 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件