I have two databases, each containing email addresses of users. I've written a script that has the sole purpose of seeing which email addresses exist in both databases.
With that being said, please look at the following loops. Each loop contains hundreds of records (I've printed out the results from each as a verification). However, when the conditional finds a match, the conditional only matches against the email address from the first match. It remains "stuck" on the one record it matched from the initial query. In other words, if it matched on "test#test.com", then all future comparisons are against "test#test.com". It's almost like I need a "next()" method to move things along from the first array.
FWIW, I'm a complete PHP noob, so I'm sure there's something obvious I'm missing here.
while($member = mysql_fetch_array($members)){
while($emailAddress = mysql_fetch_array($emailAddresses)){
if ($member['email'] == $emailAddress['email']){
echo $member['email'] . "<br/>";
}
}
}
I think the problem is you looping through a mysql-result set, there's an internal data pointer that keeps sliding up 1 step at each loop.
Try putting the results in an array first.
$adresses = array();
while($emailAddress = mysql_fetch_array($emailAddresses)){
$adresses[] = $emailAddress['email'] ;
}
Then check your result within the array
while($member = mysql_fetch_array($members)){
if(in_array($member['email'], $adresses)){
echo $member['email'];
}
}
Or perhaps you can reset the datapointer after each loop, not sure if you can do this on mysql results but it works when looping through arrays.
Related
Within the first column of every row lies a position, i.e. Software Engineer, and if the user's position matches the one in that row, the nested for loop should check in each column of that row if the given id exists in the csv string for that column. I haven't worked much with arrays in PHP and most of my experience with multidimensional arrays lies within Java so pardon my java-themed PHP code:
$csv = read_csv('/filepath/tct.csv');
$csv_rows = 75;
for($i=1;$i<$csv_rows;$i++)
{
if(strtolower($user['user_pos']) == strtolower($csv[$i][0]))
{
for($j=1;j<sizeof($csv[$i]);j++)
{
if(array_search($user['id'], explode(",",$csv[$i][$j])))
{
return true;
}
}
}
}
Unfortunately, my java doesn't seem to work and all of the existing questions concerning PHP multidimensional arrays only confuse me with the $key->$value talk. Can anyone explain to me what I need to do adjust to get this to work?
So what I was doing is a perfectly acceptable (in terms of functionality) when processing multidimensional arrays, I just neglected to place the $ before j twice in the inner loop.
The most efficient and understandable way I've found thus far is:
foreach($csv as $csv_row) {
for($i=1;$i<count($csv_row);$i++) {
//do something with $csv_row[$i]
}
}
The standard-issue nested for loop is to ensure the row names aren't iterated over since I always had row names at column[0] (despite the fact that the outer foreach will loop over the column names in row 0)
Of course, this is heavily reliant on someone using the same spreadsheet/csv layout. If it's a csv of just data, I'm sure the inner loop could be changed to:
foreach($csv_row as $csv_col {
//do something with $csv_col
}
Why don't people use for ,foreach or do..while() and why omit increment counter in while?
`<?php while ( $fa = mysql_fetch_array($sel1) )//uesd mysql_fetch_array() function in while loop
{
echo $fa['cid'];//display client id
}
// while Syntax in w3school give to used this
$x = 1;
while($x <= 5) {
echo "The number is: $x";
$x++;
}
?>//show why we don't used mysql_fecth_array() like this
This is kind of dated information. In one way you're asking a question that is just accepted along the community. It is understood better that while I have information to show ... do something. You generally wouldn't say foreach of these items ... do something though you could. However, the other problem is mysql_fetch_array returns FALSE if there are no more rows. This would not work in a foreach because it is not an array. A for would also fail because to check for the finishing of a for you have to go to some point and end.. FALSE is not a valid point of check (that I have ever tried or used).
#Michael Berkowski Adds:
As of PHP 5.4+, the mysqli_result class does have Iterator support, meaning you can do $result = mysqli_query(...); and subsequently foreach ($result as $row) {...} and it will fetch associative arrays
Though this isn't to be said the most commonly used form which is why we have the question.
You could do...while but why would you. You don't have most the information that you're going to need from the fetch array.
While is accepted and generally better. Doesn't fail and has a fall back if the mysql fails any way.
Lastly... don't use mysql_* anymore. Switch to mysqli_*. Safer.. smarter.. better.
You can perfectly use any other loop to get the query results. The reason why people mostly use while loop is because it simply is the easiest way. The reason for that is that without any extra line of code we don't know how many rows were returned and so we don't know how many times we have to iterate to get all the rows from the result. Everytime mysql_fetch_array() is executed, it gives us the next row of data and when it runs out of rows it returns false. So using while loop we basically say: While there is still a new row, we take the data from it, fetch the next row and when we run out of rows, we stop.
You can accomplish the same with for loop for example. It's just not that straightforward.
Using for loop to iterate mysql_fetch_array() :
$r = mysql_query($query);
$num_rows = mysql_num_rows($r);
for($i = 0; $i < $num_rows; $i++) {
echo mysql_fetch_array()[$id];
}
Other choice would be to place an if statement inside the for loop to check if there are any new rows, when not, we can exit the for loop.
Using the while loop we kinda combine the loop and the if statement.
I'm in WordPress. I need to compare two arrays, then unset any matches from one of them. The trouble is, one of the arrays is gettings its data from get_users, so I think I might have to convert it to strings using foreach, so I can tell it to give the user_login for the users in the array. Unless I'm wrong about that, I think what I need to be able to do is take the array, do a foreach statement so I can tell it to grab the user_logins, then convert them all back to an array. Here's all I have so far (and I'm not sure about whether I'm doing the if statement correctly in there (whether "null" is the right qualifier):
$adminnames = get_users('role=administrator');
$result = array_intersect($adminnames, $username);
if($result !== null){unset($username[$result]);}
$username is one of the attributes in the shortcode.
Also, forgive my fuzziness, if there's only one person in "username" does that mean it's not an array? 'Cause if so that might mess this up.
-- UPDATE --
If the only way to get the user_login of all administrators is to do a foreach then echo it, this might not even be possible.
I found a solution that works just great. I already do a preg_split on the $username attribute, so after I run that, this is what I've done to unset administrator usernames from the $username attribute:
$users = preg_split("/[\s,]+/",$username);
wp_get_current_user();
if(current_user_can(administrator)){
$nohidename = array_search($current_user->user_login,$users);
if($nohidename !== FALSE){unset($users[$nohidename]);
}
}
So it does it just based on whether the current user is an administrator. If not, it leaves it as is. Works great.
EDIT - An even simpler way to do it, without the array_search:
if(current_user_can(administrator)){
if($username){
unset($username);
}
}
I have code in php such as the following:
while($r = mysql_fetch_array($q))
{
// Do some stuff
}
where $q is a query retrieving a set of group members. However, certain groups have there members saved in memcached and that memcached value is stored in an array as $mem_entry. To run through that, I'd normally do the following
foreach($mem_entry as $k => $r)
{
// Do some stuff
}
Here's the problem. I don't want to have two blocks of identical code (the //do some stuff section) nested in two different loops just because in one case I have to use mysql for the loop and the other memcached. Is there some way to toggle starting off the loop with the while or foreach? In other words, if $mem_entry has a non-blank value, the first line of the loop will be foreach($mem_entry as $k => $r), or if it's empty, the first line of the loop will be while($r = mysql_fetch_array($q))
Edit
Well, pretty much a few seconds after I wrote this I ended up coming with the solution. Figure I'd leave this up for anyone else that might come upon this problem. I first set the value of $members to the memcached value. If that's blank, I run the mysql query and use a while loop to transfer all the records to an array called $members. I then initiate the loop using foreach($members as as $k => $r). Basically, I'm using a foreach loop everytime, but the value of $members is set differently based on whether or not a value for it exists in memcached.
Why not just refactor out doSomeStuff() as a function which gets called from within each loop. Yes, you'll need to see if this results in a performance hit, but unless that's significant, this is a simple approach to avoiding code repetition.
If there's a way to toggle as you suggest, I don't know of it.
Not the ideal solution but i will give you my 2 cents. The ideal would have been to call a function but if you dont want to do that then, you can try something like this:
if(!isset($mem_entry)){
$mem_entry = array();
while($r = mysql_fetch_array($q))
{
$mem_entry[] = $r;
}
}
The idea is to just use the foreach loop to do the actual work, if there is nothing in memcache then fill your mem_entry array with stuff from mysql and then feed it to your foreach loop.
I have any array
$num_list = array(42=>'0',44=>'0',46=>'0',48=>'0',50=>'0',52=>'0',54=>'0',56=>'0',58=>'0',60=>'0');
and I want to change specific values as I go through a loop
while(list($pq, $oin) = mysql_fetch_row($result2)) {
$num_list[$oin] = $pq;
}
So I want to change like 58 to 403 rather then 0.
However I always end up getting just the last change and non of the earlier ones. So it always ends up being something like
0,0,0,0,0,0,0,0,0,403
rather then
14,19,0,24,603,249,0,0,0,403
How can I do this so it doesn't overwrite it?
Thanks
Well, you explicititly coded that each entry should be replaced with the values from the database (even with "0").
You could replace the values on non-zero-values only:
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if ($pq !== "0") $num_list[$oin] = $pq;
}
I don't get you more clear, i thought your asking this only. Check this
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if($oin==58) {
$num_list[$oin] = $pq;
}
}
In my simulated tests (although You are very scarce with information), Your code works well and produces the result that You want. Check the second query parameter, that You put into array - namely $pg, thats what You should get there 0,0,0,0,0...403 OR Other thing might be that Your $oin numbers are not present in $num_list keys.
I tested Your code with mysqli driver though, but resource extraction fetch_row is the same.
Bear in mind one more thing - if Your query record number is bigger than $numlist array, and $oin numbers are not unique, Your $numlist may be easily overwritten by the folowing data, also $numlist may get a lot more additional unwanted elements.
Always try to provide the wider context of Your problem, there could be many ways to solve that and help would arrive sooner.