繁体   English   中英

PDO数组中的重复值

[英]PDO duplicate values in array

我需要从数据库中获取一些货币ID,这是我的代码

$arr = [];

$currency_codes = array("USD", "RUB");
$currency_codes_in = implode(',', array_fill(0, count($currency_codes), '?'));
$query = "SELECT `curr_id` FROM `dictionary_currency` WHERE `curr_code` IN (". $currency_codes_in .")";
$stmt = $db->prepare($query); 
foreach ($currency_codes as $k => $id) {
    $stmt->bindValue(($k+1), $id);
}

$stmt->execute();
$currencies = $stmt->fetchAll();

foreach($currencies as $currency)
{
    foreach($currency as $key => $value)
    {
        $arr[] = $value;
    }
}
print_r($arr);
exit();

这是$currencies数组

Array
(
    [0] => Array
        (
            [curr_id] => 643
            [0] => 643
            [curr_code] => RUB
            [1] => RUB
        )

    [1] => Array
        (
            [curr_id] => 840
            [0] => 840
            [curr_code] => USD
            [1] => USD
        )

)

这是$arr

Array
(
    [0] => 643
    [1] => 643
    [2] => 840
    [3] => 840
)

我不明白为什么我会在数组中得到重复的值以及如何防止它出现?

PDO是一个数据库包装程序,可以为您做很多事情。 例如,

因此,实际上您需要的代码数量比现在少了两倍:

$currency_codes = array("USD", "RUB");
$currency_codes_in = implode(',', array_fill(0, count($currency_codes), '?'));
$query = "SELECT `curr_id` FROM `dictionary_currency` WHERE `curr_code` IN ($currency_codes_in)";
$stmt = $db->prepare($query); 
$stmt->execute($currency_codes);
$arr = $stmt->fetchAll(PDO::FETCH_COLUMN);

或者我宁愿提议使其像

$query = "SELECT curr_code, curr_id FROM dictionary_currency WHERE `curr_code` IN ($currency_codes_in)";
$stmt = $db->prepare($query); 
$stmt->execute($currency_codes);
$arr = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

循环是有问题的:

foreach($currencies as $currency) {
     foreach($currency as $key => $value) {
           $arr[] = $value;
     }
}

只需使用简单

foreach($currencies as $currency) {
    $arr[] = $currency[0];
}

编辑#1:

使用您的$currencies和旧查询,我得到了以下信息:

Array
(
    [0] => Array
    (
        [curr_id] => 643
        [0] => 643
        [curr_code] => RUB
        [1] => RUB
    )

    [1] => Array
    (
        [curr_id] => 840
        [0] => 840
        [curr_code] => USD
        [1] => USD
    )
)

Array
(
    [0] => 643
    [1] => 643
    [2] => RUB
    [3] => RUB
    [4] => 840
    [5] => 840
    [6] => USD
    [7] => USD
)

我知道这个问题越来越老了。 但是,这是防止PDO重复值的解决方案。 只是使用这个:

$stmt->fetchAll(PDO::FETCH_ASSOC);

代替这个:

$stmt->fetchAll();

使用以下查询$ query =“ SELECT DISTINCT curr_id FROM dictionary_currency WHERE curr_code IN(”。$ currency_codes_in。“)”;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM