compare two arrays then unset the matches in php - php

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);
}
}

Related

some of session varibles gets back to the old value

i use centos 6.6, php 5.3.4
I have a php script called in an iframe(let's call it a.php)..
when it's called as a.php?p_type=1&item_num=1234,
it saves an array into session.
sometimes, it merges two array in session and save it into session again
but the merging doesnt work..
here is the simplified code.
(i will hide minor details for brevity)
header('P3P: CP="CAO PSA OUR"');
session_start();
$p_type_val = $_GET["p_type"];
$sess_var = "a".$p_type_val;
$some_array = $_SESSION[$sess_var];
if(isset($_GET["item_num"])
{
$some_array[] = $_GET["item_num"];
$_SESSION[$sess_var] = $some_array;
}
if($p_type_val == 1) // when p_type is 1, merge two arrays in the session.
{
$sess_var2 = "a"."2";
$some_array2 = $_SESSION[$sess_var2];
$_SESSION[$sess_var2] = array_merge($some_array,$some_array2);
}
else if($p_type_val == 2)
{
$some_array2 = $_SESSION["p2"];
print_r($some_array2);
}
.........
first, i called a.php?p_type=1&item_num=1234, then i called a.php?p_type=2 lator,
then the newly added item number 1234 to "a2" is lost. the values in the array "a2" is back to the old values.
but the values in "a1" are no problem.
i checked the session file in /var/lib/php/session directory and found all the result is as i expected.
after i called a.php?p_type=1, the values in the file are as i expected.
but right after a.php?p_type=2, the values go back to the old ones.
the funny thing is when i call a.php?p_type=2 twice with diffrent item_nums,
the array "a2" works correctly.
i don't know why the some values in a session go back to old values.
where should i start debugging for this..
any suggestion would be appreciated..
i guess your problem is you don't read the manual about it, no rudeness intended but it clearly say there than when you merge two arrays that can happend, explain also the 'whys' of it, because of that i suggest you read the stuff entirely, no kittin, there is some overlapping examples explained in the section of examples of the manual too, and explain how to avoid/use that "problem".
it textualy says:
"If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended."
So, probably you are using the same string values in both $_SESSION variables, or both of them have the same int to index data, i told you, it is necesary to see the creation of the $_SESSION, otherwise i cant see the compositions of that arrays that you are merging and, because of that, i can't suggest one way to solve the problem oriented to your necesitys.
which, in fact, you are not saying, you are merging two $_SESSION variables but not saying why is that for, and taking that in perspective, the rest of the people cannot even know if that is the right aproach for what you want.
Anyway, your solution is to read that part of the manual & instanciate that to your code.
http://php.net/manual/en/function.array-merge.php
Have a good day

Wordpress $wpdb->get_results(...) issues with comparing strings

I am trying to iterate through the rows in a phpbb table called phpbb_posts and extract each entry in phpbb's "post_subject" column and compare its value with a predefined string in Wordpress PHP file but I am having some issues - the expressions don't evaluate to true.
My phpBB's tables are installed in WP's database so I have full access to the values.
See the code below to demonstrate the issue I am having.
function matchPhpBBTopic()
{
global $wpdb;
$wp_post_title_string = get_the_title();
$result = $wpdb->get_results("SELECT * FROM phpbb_posts");
foreach($result as $row)
{
$phpbb_post_title_array = array($row->post_subject);
$phpbb_post_title_string = implode("", $phpbb_post_title_array);
// One of the values in $row->post_subject contains
// the value in $wp_post_title_string
if (strcmp($wp_post_title_string, $phpbb_post_title_string) == 0)
{
// This line never runs but the $wp_post_title_string value
// is there, in the table, I've printed it and it's there
echo 'We found a match!<br>';
}
}
}
Any assistance would be appreciated.
So in other words, I have a topic posted in WP and I have exactly the same topic posted in phpBB and I want to iterate through the phpBB's table and when I find the topic, I want to run some code. I don't understand why the "if" expression does not run.
Couldn't you just do:
if ($wp_post_title_string == $phpbb_post_title_string) {}
I don't think strcmp() is appropriate. It converts the string to encoding numbers.
http://us1.php.net/strcmp
Also check for lower and upper case, spaces, and different encodings.
Do strtolower() and trim() first and see what you get.
Also looks like you're imploding subject and title, so don't think they'll match.

PHP Change Array Over and Over

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.

PHP Compare Two Arrays?

I'm trying to compare two entries in a database, so when a user makes a change, I can fetch both database entries and compare them to see what the user changed, so I would have an output similar to:
User changed $fieldName from $originalValue to $newValue
I've looked into this and came across array_diff but it doesn't give me the output format I need.
Before I go ahead and write a function that does this, and returns it as a nice $mtextFormatDifferenceString, can anyone point me in the direction of a solution that already does this?
I don't want to re-invent the wheel..
Since you require "from $originalValue to $newValue", I would go ahead and select the two rows, put them in assoc arrays, then foreach through the keys, saving the ones that aren't equal. Kind of like:
$fields = array_keys($row1);
$changedFields = array();
foreach ($fields as $field) {
if ($row1[$field] != $row2[$field]) {
$changedFields[] = $field;
}
}
I realize you were asking about the existence of pre-built wheels but I felt the solution was pretty simple.
?>
Although you didn't define what format you needed, but well-known diff algorithm is probably for you. Google for PHP diff algorithm and you'll find some suggestions I am sure.
You could get the changed values ($newValue) with array_diff_assoc and then just use the keys ($fieldName) to find the original value $originalValue and output it in anyformat you want

Most efficient way to get data from the database to session

What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have:
$sql = "SELECT * FROM users WHERE username='" . mysql_escape_string($_POST['username']) . "' AND password='" . mysql_escape_string(md5($_POST['password'])) . "'";
$result = mysql_query($sql, $link) or die("There was an error while trying to get your information.\n<!--\n" . mysql_error($link) . "\n-->");
if(mysql_num_rows($result) < 1)
{
$_SESSION['username'] = $_POST['username'];
redirect('index.php?p=signup');
}
$_SESSION['id'] = mysql_result($result, '0', 'id');
$_SESSION['fName'] = mysql_result($result, '0', 'fName');
$_SESSION['lName'] = mysql_result($result, '0', 'lName');
...
And before anyone asks yes I do really need to 'SELECT
Edit: Yes, I am sanitizing the data, so that there can be no SQL injection, that is further up in the code.
I came up with this and it appears to work.
while($row = mysql_fetch_assoc($result))
{
$_SESSION = array_merge_recursive($_SESSION, $row);
}
Most efficient:
$get = mysql_query("SELECT * FROM table_name WHERE field_name=$something") or die(mysql_error());
$_SESSION['data'] = mysql_fetch_assoc($get);
Done.
This is now stored in an array. So say a field is username you just do:
echo $_SESSION['data']['username'];
Data is the name of the array - username is the array field.. which holds the value for that field.
EDIT: fixed some syntax mistakes :P but you get the idea.
OK, this doesn't answer your question, but doesn't your current code leave you open to SQL Injection?
I could be wrong, never worked in PHP, just saw the use of strings in the SQL and alarm bells started ringing!
Edit:
I am not trying to tamper with your post, I was correcting a spelling error, please do not roll back.
I am not sure what you mean by "large amounts of data", but it looks to me like you are only initializing data for one user? If so, I don't see any reason to optimize this unless you have hundreds of columns in your database with several megabytes of data in them.
Or, to put it differently, why do you need to optimize this? Are you having performance problems?
What you are doing now is the straight-forward approach, and I can't really see any reason to do it differently unless you have some specific problems with it.
Wrapping the user data in a user object might help some on the program structure though. Validating your input is probably also a good idea.
#Unkwntech
Looks like you are correct, but following a Google, which led here looks like you may want to change to mysql_real_escape_string()
As for the edit, I corrected the spelling of efficient as well as removed the "what is the".. Since that's not really required since the topic says it all.
You can review the edit history (which nicely highlights the actual changes) by clicking the "edited a min ago" text at the bottom of your question.
Try using json for example:
$_SESSION['data'] = json_encode(mysql_fetch_array($result));
Is the implementation of that function faster than what he is already doing?
Does anyone else have trouble entering ] into markdown? I have to paste it in
Yes, it's bugged.
#Anders - there are something like 50-75 columns.
Again, unless this is actually causing performance problems in your application I would not bother with optimizing it. If, however, performance is a problem I would consider only getting some of the data initially and lazy-loading the other columns as they are needed.
If Unkwntech's suggestion does indeed work, I suggest you change your SELECT statement so that it doesn't grab everything, since your password column would be one of those fields.
As for whether or not you need to keep this stuff in the session, I say why not? If you're going to check the DB when the user logs in (I'm assuming this would be done then, no?) anyway, you might as well store fairly non-sensitive information (like name) in the session if you plan on using that information throughout the person's visit.
It's not so much that it causing performance problems but that I would like the code to look a bit cleaner.
Then wrap the user data in a class. Modifyng $_SESSION directly looks somewhat dirty. If you want to keep the data in a dictionary—which you can still do even if you put it in a separate class.
You could also implement a loop that iterates over all columns, gets their names and copy the data to a map with the same key names. That way your internal variables—named by key in the dictionary—and database column names would always be the same. (This also has the downside of changing the variable name when you change the column name in the database, but this is a quite common and well-accepted trade-off.)
Try using json for example:
$_SESSION['data'] = json_encode(mysql_fetch_array($result));
Edit
Later you then json_decode the $_SESSION['data'] variable and you got an array with all the data you need.
Clarification:
You can use json_encode and json_decode if you want to reduce the number of lines of code you write. In the example in the question, a line of code was needed to copy each column in the database to the SESSION array. Instead of doing it with 50-75 lines of code, you could do it with 1 by json_encoding the entire database record into a string. This string can be stored in the SESSION variable. Later, when the user visits another page, the SESSION variable is there with the entire JSON string. If you then want to know the first name, you can use the following code:
$fname = json_decode($_SESSION['data'])['fname'];
This method won't be faster than a line by line copy, but it will save coding and it will be more resistant to changes in your database or code.
BTW
Does anyone else have trouble entering ] into markdown? I have to paste it in.

Categories