MySQL的选择查询与PHP foreach [英] mysql select query with php foreach
问题描述
我正在尝试编写一个函数,该函数将从表中获取ID,然后希望将所有ID都包含在数组中,以便将这些ID用于另一个函数中进行处理. 我写了下面的内容,但它不是数组方法,而且它两次打印id.我在网上搜索,他们都建议使用mysql_fetch_assoc并删除每个..但就我而言,我正在使用zend适配器fetchAll来获取输出.请让我知道如何才能在数组中获取ID,并且也只能获取一次,以便我可以传递此数组,并且每个ID都会被一个一个地处理..现在,我拥有的只是在处理第一个ID之后才停止.谢谢.
I am trying to write a function where I will get the id's from a table and then I want to have the all the id's in the array so that these id's used in another function to be processed. I wrote the below but it's not array method and also it's printing the id's twice. I searched online and they all suggest to use mysql_fetch_assoc and remove for each..but in my case I am using the zend adapter fetchAll to get the output. Please let me know how I can get the id's in the array and also only once so that I can pass this array and each id is processed one by one..right now with what I have is just stopping after the first one is processed. Thanks.
function getID()
{
$sql = 'SELECT user_id FROM users WHERE ready = "1" ';
$idList = $this->getAdapter()->fetchAll($sql);
if(!empty($idList)) {
foreach($idList as $value) {
echo $value['user_id']."\n";
}
}
}
Output
201
223
231
334
201
223
231
334
推荐答案
尝试一下.
function getIDs() {
$result = array();
$sql = 'SELECT user_id FROM users WHERE ready = "1" ';
$idList = $this->getAdapter()->fetchAll($sql);
if(!empty($idList)) {
foreach($idList as $value) {
echo $value['user_id']."\n";
array_push(result, $value['user_id']);
}
}
// $result = array_unique($result);
return $result;
}
然后您将通过以下方式获取数组:
You will then get the array by:
$bunch_of_ids = getIDs();
您应该弄清楚为什么要重复它们,但是如果不能,可以使用以下方法使数组内容唯一:
You should figure out why they are being duplicated, but in case you can't, you can make the array content unique with:
$result = array_unique($result);
将其放在函数内return $result;
之前.我已经在上面的函数中对其进行了评论,因为最好找出为什么它首先要被复制.正如我在对您的问题的评论中指出的那样,请确保该函数没有被调用两次.还要检查数据库中是否有重复的条目(尽管如果'user_id'是主键,那应该是不可能的.)
Put that right before return $result;
inside the function. I've commented it in the function above because would be much better to find out why it's being duplicated in the first place. As I noted in a comment to your question, please make sure that the function isn't being called twice. Also check the database for duplicate entries (although that shouldn't be possible if 'user_id' is a primary key).
(还请注意,我将函数重命名为getIDs(),因为让getID()函数返回多个值是没有意义的.:))
(Please also note that I renamed the function to getIDs() because it makes no sense to have a getID() function returning multiple values. :) )
这篇关于MySQL的选择查询与PHP foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!