php - PDO 数组中的重复值

标签 php mysql arrays pdo

我需要从数据库获取一些货币 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);

关于php - PDO 数组中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36420966/

相关文章:

php - 如何检查 PHP 是否启用了 gzip 压缩?

php - 为什么 next_post_link() 不能与 WP_Query 一起使用?

php - 将 session 数组存储在数据库中

mysql - 列表中的 SQL 中缺少哪些值?

javascript - PHP $$var 的 JS 等价物是什么?

php - EditableGrid, "addcolumn"循环

mysql - 改变 '/var/lib/mysql/' : Permission denied 的所有权

php - 如何使用 PHP 对 JSON 数组进行排序

javascript - 需要在 React Native 中将对象转换为 FlatList 的数组

php - 警告 : implode() [function. 内爆]:传递的参数无效