2

我有以下代码:

$get_countries = "SELECT country FROM blahs WHERE country IS NOT NULL ORDER BY country";
$data_get_countries = mysqli_query($dbc, $get_countries);

while ($row_get_countries = mysqli_fetch_array($data_get_countries)) {
    $country_tabs = array_unique($row_get_countries);
    foreach ($country_tabs as $country_tab) {
        echo '<div>' . $country_tab . '</div>';
        var_dump($country_tab);
        var_dump($country_tabs);

    }
}

现在 var_dump($country_tab) 输出:

string 'DE' (length=2)
string 'GB' (length=2)
string 'SE' (length=2)
string 'US' (length=2)
string 'US' (length=2)
string 'US' (length=2)
string 'US' (length=2)

和 var_dump($country_tabs):

array
    0 => string 'DE' (length=2)
array
    0 => string 'GB' (length=2)
array
    0 => string 'SE' (length=2)
array
    0 => string 'US' (length=2)
array
    0 => string 'US' (length=2)
array
    0 => string 'US' (length=2)
array
    0 => string 'US' (length=2)

我想要实现的目标是让我的代码不显示相同的国家!array_unique($country_tabs) 不起作用,因为我在输出中有更多数组。

4

4 回答 4

3

采用SELECT DISTINCT country FROM blahs WHERE country IS NOT NULL ORDER BY country

它将删除每个重复的值。

于 2012-08-02T18:22:23.283 回答
2

您最好像这样在数据库查询中获取唯一值:

SELECT DISTINCT country FROM blahs WHERE country IS NOT NULL ORDER BY country

请注意,我添加了 DISTINCT 关键字来执行您要执行的操作。

于 2012-08-02T18:21:27.073 回答
2

修改您的查询以仅获取唯一的国家/地区:

$get_countries = "SELECT DISTINCT country FROM blahs WHERE country IS NOT NULL ORDER BY country";
于 2012-08-02T18:21:47.147 回答
2

使用 mysql 查询获取唯一国家:

SELECT country 
FROM blahs 
WHERE country IS NOT NULL
GROUP BY country
ORDER BY country

这样优化多了!

于 2012-08-02T18:22:28.623 回答