PDO数组中的重复值 [英] PDO duplicate values in array
本文介绍了PDO数组中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从数据库中获取一些货币ID,这是我的代码
I need to get some currency ids from db, this is my code
$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
)
我不明白为什么我会在数组中得到重复的值以及如何防止重复出现?
I don't understand why I get duplicate values in arrays and how to prevent it?
推荐答案
循环有问题:
foreach($currencies as $currency) {
foreach($currency as $key => $value) {
$arr[] = $value;
}
}
只需使用简单的
foreach($currencies as $currency) {
$arr[] = $currency[0];
}
编辑#1:
Edit #1:
使用您的$currencies
和旧查询,我得到以下信息:
Using your $currencies
and old query, I got the following:
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数组中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文