问题
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
回答1:
Try this.
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);
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).
(Please also note that I renamed the function to getIDs() because it makes no sense to have a getID() function returning multiple values. :) )
回答2:
this function is correct, but if you want an array:
if(!empty($idList)) {
foreach($idList as $value) {
$array[] = $value['user_id'];
}
and if 'user_id'
really are repeated:
$array = array_unique($array);
回答3:
Your function looks correct to me, are you sure you are not calling it twice to explain the double output?
回答4:
<?php
function getID(){
$get = mysql_query("SELECT user_id FROM users WHERE ready = '1'", $yhteys);
for ($i = 0; $i < mysql_num_rows($get); $i++) {
$id = mysql_result($get, $i, "user_id");
$userids[] = $id;
}
return $userids;
}
?>
回答5:
I think that code is fine. I don't see any mistake there.
来源:https://stackoverflow.com/questions/7417275/mysql-select-query-with-php-foreach