PHP Compare Two Arrays? - php

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

Related

alphanumeric sorting with php and preg_match

I have an array called $itemArray[] that contains a set of strings, such as:
myItem_1,
myItem_2,
myItem_3,
myItem_4,
anotherName_1,
anotherName_2,
anotherName_3,
anotherName_4
I also have the following code that goes through the array and filters out the ones that contain 'myItem'.
The loop works, however, it returns results in varied order. Is there a way to sort the result of the array so
that it lists them alphanumerically?
foreach($itemArray as $item) {
if (preg_match('/myItem/',$item))
echo '$item';
}
I don't have much experience with php and would definitely appreciate the help! Thank you!
PHP supports lots of ways to sort arrays, see how they work here. You could run it as asort($itemArray).
The right way to solve this is by sorting the array prior to outputting it. Something along the lines of:
asort($itemArray);
foreach($itemArray as $item) {
if (preg_match('/myItem/',$item))
array[index++] = $item;
}

compare two arrays then unset the matches in 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);
}
}

Is there an algorithm to output all possible combinations of two sets of elements?

I am writing an application in PHP where users can enter two sets of information and have every possible combination of the two sets printed out. The goal is to use it as a teaching tool for learning language by practicing different patterns of a question and answer.
For example, we may practice the question "Have you ever tried...?" plus one of four activities, such as bungee jumping, para sailing, skydiving, and scuba diving. There would also be four possible answers:
Yes I have, and I enjoyed it.
Yes I have, but I didn't like it.
No I haven't, but I want to try it.
No I haven't, and I don't want to try it.
The user would input the two sets of data, and the application would then print sheets of cards containing all possible combinations of the questions and answers. For example, card 1 would look like this:
skydiving: Yes I have, and I enjoyed it.
scuba diving: Yes I have, but I didn't like it.
parasailing: No I haven't, but I want to try it.
bungee jumping: No I haven't, and I don't want to try it.
The next card might then look like this:
skydiving: Yes I have, but I didn't like it.
scuba diving: No I haven't, but I want to try it.
parasailing: No I haven't, and I don't want to try it.
bungee jumping: Yes I have, and I liked it.
So as you can see, there are many different possible combinations. The idea would be that both lists would be of the same length to allow all of the possibilities to be printed out. It is also important that no question or answer gets used more than once on any card, and that two cards can be alike. What would be the best way to go about this? The actual input and output is not the problem--I've done similar things before. I just need the algorithm to produce the combinations.
EDIT: I guess what I'm really after is to keep the activities in the same order for each card, but have every possible combinations of answers. So what I really need is to be able to produce the following set of indexes for getting data out of the answers array. So I really want something more like this:
0,1,2,3
0,1,3,2
0,2,1,3
0,2,3,1
0,3,1,2
0,3,2,1
1,0,2,3
1,0,3,2
1,2,0,3
1,2,3,0
...and so on until all possible combinations have been produced.
Try this:
$activities = array(); // Input all your activities as elements here.
$responses = array(); // Input all your responses as elements here.
foreach ($activities as $activity) {
foreach ($responses as $response) {
echo $activities.' '.$response."\n";
}
}
OK, with the new criteria, I think I understand a little better.
Try recursion. My solution is messy as hell but I can walk you through it:
$activities = array('a', 'b', 'c', 'd'); // Input all your activities as elements here.
$responses = array(1, 2, 3, 4); // Input all your responses as elements here.
// Recursive function outputCombos accepts both arrays (for eventual output).
// $workingArray is the array of the current branch we're working with.
function outputCombos ($activities, $responses, $workingArray) {
// Once the working array has been loaded to the maximum amt, print everything out.
if (count($workingArray) == count($responses)) {
echo "Combo\n";
for ($x = 0; $x < count($activities); $x++) {
echo $activities[$x].'::'.$workingArray[$x]."\n";
}
// If the working array isn't full, add an element that isn't currently in the working array, and recursively run the function again.
} else {
foreach ($responses as $response) {
// Iterate through list of all possible responses, add it into a new working array and run the function if the response hasn't been used in this working array.
if (!in_array($response, $workingArray)) {
$newArray = $workingArray;
$newArray[] = $response;
outputCombos($activities, $responses, $newArray);
}
}
}
}
foreach ($responses as $response) {
echo '<pre>';
// Start each branch of tree with unique response (should be 4 in this case).
outputCombos($activities, $responses, array($response));
echo '</pre>';
}

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.

Using foreach to create grid

I am creating a grid in GD and was wondering if this is the right way to do it.
I have 2 arrays. One contains all X values, the other contains all Y values.
foreach ($xpointsArray as $xvalue) {
foreach ($ypointsArray as $yvalue) {
// Draw point at coordinates $xvalue, $yvalue
}
}
I just think there must be a more elegant way to set this up, and I would like to further
access the points values without doing this every time.
What you're doing is correct. There's possibly some more elegant solutions using a single two dimensional array, but either way you have to iterate through two loops.
Additionally, using a two dimensional array you could reference specific points by $Array[$x][$y] to get a specific point.
foreach, while, for are nice and I personally would prefer them, but since you are asking, what about using array_walk()?
array_walk($array1, "print_sudoku_field", $array2);

Categories