php, how to compare the 2 arrays from different queries? - php

i have 2 queries, and i get back some data by doing a whyle loop.
from the first query if i do print_r($final_key);i get:
hey1
hey2
hey3
from the second one, if i do print_r($final_key2); i get:
hey1 test
hey2 test1
hey3
what i am trying to do is to compare the 2 arrays and check for words that match
and i can't do it directly from the database
any ideas?
thanks
edit:
here is my query 1:
while ($keywords = mysql_fetch_array($keys1, MYSQL_ASSOC)){
foreach ($keywords as $key) {
$plus = '+';
$pos = strripos($key, $plus);
if ($pos === false) { } else {
$clean_plus = preg_replace("/[\+]/", '', $key);
$final_key = str_replace("'", "", $clean_plus);
print_r($final_key);
echo '<br>';
}
}
}
and the second one:
<?php
while ($keywords = mysql_fetch_array($keys)){
if($keywords['kword'] != ''){
echo $keywords['kword'];
} } ?>
i am tryingt o match $final_key against $keywords['kword'];

Use array_intersect:
array_intersect($array1, $array2, ...);
from the array_intersect documentation:
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

Use array_intersect which returns an array containing values in both arrays.
If you want the keys to match, use array_intersect_assoc.

Loop over one array, and on each iteration, loop the other.
<?php
foreach($array as $item){
foreach($array2 as $item2){
if($item == $item2){
$array3[] = $item;
}
}
}
?>
This will create an array of matches, which you can then do with as you will.

Related

Replace array value with more than one values

I have an array like this,
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
I want to find any value with an ">" and replace it with a range().
The result I want is,
array(
1,2,3,4,5,6,7,8,9,10,11,12, '13.1', '13.2', 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
);
My understanding:
if any element of $array has '>' in it,
$separate = explode(">", $that_element);
$range_array = range($separate[0], $separate[1]); //makes an array of 4 to 12.
Now somehow replace '4>12' of with $range_array and get a result like above example.
May be I can find which element has '>' in it using foreach() and rebuild $array again using array_push() and multi level foreach. Looking for a more elegant solution.
You can even do it in a one-liner like this:
$array = array(1,2,3,'4>12','13.1','13.2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,#range(...array_slice(explode(">","$c>$c"),0,2)));},
[]
));
I avoid any if clause by using range() on the array_slice() array I get from exploding "$c>$c" (this will always at least give me a two-element array).
You can find a little demo here: https://rextester.com/DXPTD44420
Edit:
OK, if the array can also contain non-numeric values the strategy needs to be modified: Now I will check for the existence of the separator sign > and will then either merge some cells created by a range() call or simply put the non-numeric element into an array and merge that with the original array:
$array = array(1,2,3,'4>12','13.1','64+2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,strpos($c,'>')>0?range(...explode(">",$c)):[$c]);},
[]
));
See the updated demo here: https://rextester.com/BWBYF59990
It's easy to create an empty array and fill it while loop a source
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$res = [];
foreach($array as $x) {
$separate = explode(">", $x);
if(count($separate) !== 2) {
// No char '<' in the string or more than 1
$res[] = $x;
}
else {
$res = array_merge($res, range($separate[0], $separate[1]));
}
}
print_r($res);
range function will help you with this:
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$newArray = [];
foreach ($array as $item) {
if (strpos($item, '>') !== false) {
$newArray = array_merge($newArray, range(...explode('>', $item)));
} else {
$newArray[] = $item;
}
}
print_r($newArray);

How to check if Each value in $array1 the present in $array2 or not

I have known the cause of the problem, not in the code.
Content of the field at the base value of each line separately
So used str_replace to delete the line
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array1 = str_replace("\n","",$array1);
$array2 = explode(",",$query[filed2]);
$array2 = str_replace("\n","",$array2);
foreach($array1 as $value)
{
if (in_array($value,$array2))
{
//true
}else{
//false
}
}
I have a problem when I check if Each value in $array2 is present in $array1 or not
Table data:
filed1 | filed2
ahmed,jon,maya,omar | omar,maya
My code:
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array2 = explode(",",$query[filed2]);
$length = count($array1);
for ($i = 0; $i < $length; $i++)
{
if (in_array($array1[$i] , $array2))
{
//true
}else{
//false
}
}
or this:
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array2 = explode(",",$query[filed2]);
foreach($array1 as $value)
{
if (in_array($value,$array2))
{
//true
}else{
//false
}
}
My problem is my code doesn't work good, I am sure that my query gives the results and arrays too.
Output of array1:
Array ( [0] => maya [1] => omar [2] => ahmed [3] => join)
Output of array2:
Array ( [0] => omar [1] => maya )
So, where is the error in my code?!
Note :
I don't want check all value from array2 are in array1, I want check if Each value in $array2 is present in $array1 or not - focus on this word Each value not all value
Like:
if (in_array('omar',$array1))
{
echo 'found';
}else{
echo 'not found'; }
if (in_array('maya',$array1))
{
echo 'found';
}else{
echo 'not found';
}
if (in_array('jon',$array1))
{
echo 'found';
}else{
echo 'not found';
}
etc ...
But I do not want it this way, I want it inside a loop.
Yes you can use a loop in this case if you really want to, a simple foreach should suffice:
$array1 = array_map('trim', $array1); // on explode make sure remove trailing/leading spaces
$array2 = array_map('trim', $array2);
foreach($array1 as $name) { // so each value of array1
if(in_array($name, $array2)) { // is compared inside the contents of array2
// if found
echo "$name is found in " . '$array2';
} else {
echo "$name is NOT found in " . '$array2';
}
}
I think you should be iterating over array2 so all values of array2 are checked, not the other way around, because you said: "
check if Each value in $array2...
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query['filed1']);
$array2 = explode(",",$query['filed2']);
foreach($array2 as $value)
{
if (in_array($value,$array1))
{
//true
}else{
//false
}
}
I have known the cause of the problem, not in the code ...
Content of the field at the base value of each line separately
So used str_replace to delete the line
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array1 = str_replace("\n","",$array1);
$array2 = explode(",",$query[filed2]);
$array2 = str_replace("\n","",$array2);
foreach($array1 as $value)
{
if (in_array($value,$array2))
{
//true
}else{
//false
}
}
array_diff() is a single function approach to getting an array of items not present in further arrays
$array1 = array('ahmed','jon','maya','omar');
$array2 = array('omar','maya');
$result = array_diff($array1,$array2); // Array ( [0] => ahmed [1] => jon )
you may need to switch parameter order to achieve your desired outcome.
you can also use array_intersect() to perform the reverse
#Ghost's solution produced the correct output, but as you state, you know the problem isn't your code. Apparently the problem is that the format of the data you are querying isn't quite matching. So, here is how you can approach debugging this problem:
var_dump() the data
The likely suspect is that some of the data have padding. (It's odd that #Ghost's suggestion of trimming the results didn't work.)
$array1 = explode(",",$query['filed1']);
$array2 = explode(",",$query['filed2']);
var_dump($array1);
echo "\n";
var_dump($array2);
echo "\n";
Inspect comparisons in the iteration
The above should reveal the problem. If not, you could take it a step deeper and see which exact comparison is failing in the in_array. If you don't have xdebug available, just loop within the loop:
foreach ($array1 as $value) {
if (in_array($value, $array2)) {
echo "\n[$value found in \$array2]\n";
} else {
echo "\n[$value NOT found in \$array2]\n";
}
foreach ($array2 as $value2) {
if ($value !== $value2) {
echo "\$array1's '$value' !== \$array2's '$value2'\n";
} else {
echo "\$array1's '$value' === \$array2's '$value2'\n";
}
}
}
The output will show you exactly what is wrong.
Note: You should include filed1 and filed2 in quotes since you are using them as string keys. When PHP parses your code, it will emit a notice (error) and fall back on interpreting it as a string.

Count occurrences of a specific value in multidimensional array

Let's say I have a multidimensional array like this:
[
["Thing1", "OtherThing1"],
["Thing1", "OtherThing2"],
["Thing2", "OtherThing3"]
]
How would I be able to count how many times the value "Thing1" occurs in the multidimensional array?
you can use array_search for more information see this http://www.php.net/manual/en/function.array-search.php
this code is sample of this that is in php document sample
<?php
function recursiveArraySearchAll($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
$resultkeys;
while($it->valid()) {
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND (strpos($it->current(), $needle)!==false)) { //$it->current() == $needle
$resultkeys[]=$aIt->key(); //return $aIt->key();
}
$it->next();
}
return $resultkeys; // return all finding in an array
} ;
?>
If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
http://www.php.net/manual/en/function.array-keys.php
Try this :
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
echo "<pre>";
$res = array_count_values(call_user_func_array('array_merge', $arr));
echo $res['Thing1'];
Output :
Array
(
[Thing1] => 2
[OtherThing1] => 1
[OtherThing2] => 1
[Thing2] => 1
[OtherThing3] => 1
)
It gives the occurrence of each value. ie : Thing1 occurs 2 times.
EDIT : As per OP's comment : "Which array do you mean resulting array?" - The input array. So for example this would be the input array: array(array(1,1),array(2,1),array(3,2)) , I only want it to count the first values (1,2,3) not the second values (1,1,2) – gdscei 7 mins ago
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
$res = array_count_values(array_map(function($a){return $a[0];}, $arr));
echo $res['Thing1'];
function showCount($arr, $needle, $count=0)
{
// Check if $arr is array. Thx to Waygood
if(!is_array($arr)) return false;
foreach($arr as $k=>$v)
{
// if item is array do recursion
if(is_array($v))
{
$count = showCount($v, $needle, $count);
}
elseif($v == $needle){
$count++;
}
}
return $count;
}
Using in_array can help:
$cont = 0;
//for each array inside the multidimensional one
foreach($multidimensional as $m){
if(in_array('Thing1', $m)){
$cont++;
}
}
echo $cont;
For more info: http://php.net/manual/en/function.in-array.php
try this
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
$abc=array_count_values(call_user_func_array('array_merge', $arr));
echo $abc[Thing1];
$count = 0;
foreach($array as $key => $value)
{
if(in_array("Thing1", $value)) $count++;
}
If you prefer code brevity zero global scope pollution, you can count every value and access the one count that you do want:
echo array_count_values(array_merge(...$array))['Thing1'] ?? 0;
If you don't want to bother counting values where the count will never be needed, then you can visit leafnodes with array_walk_recursive() and +1 everytime the target value is encountered.
$thing1Count = 0;
array_walk_recursive($array, function($v) use(&$thing1Count) { $thing1Count += ($v === 'Thing1'); });
echo $thing1Count;
Both snippets return 2. Here's a Demo.

PHP array does not sort at all

I have a problem with sorting of an array.
$infoGroup is the result of a 'ldap_get_entries' call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
Henrik Lindbom
Klaus Rödel
Admin
Bernd Brandstetter
proxyuser
Patrik Löfström
Andreas Galic
Martin Stalder
Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that foreach() loop. Essentially, since you are creating the array element in the iteration of the first loop, the natsort() only has 1 element to sort and your nested foreach() loop is only outputting that 1 element, which is then unset() at the second and further iterations...
Extract that second foreach() that sorts and outputs and remove the unset() from the top of the first loop. This should output your desired results.
Something like this...
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
$ai = 0;

Compare two arrays and merging in PHP

I have two arrays:
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
Here $array1 has keys and values. Now I want to take the first value from $array1(as 1) and I want to check if this is repeated in this array .
Here 1 is repeated two times so I want to take the two keys 1,10 and display the corresponding values of these keys from $array2. If the value in $array1 is not repeated then I want to just display the value of this key from $array2.
I want to get the output as follows:
Hello Test
check
error
That means in $array1 1,10 keys have the same value so the value of 1 and the value of 10 from $array2 is merged then displayed.
Like 12 has 0 this is not repeated so simply take value of 12 from $array2.
Like 13.
How can I do this?
<?php
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
$groupedKeys = array();
foreach($array1 as $key=>$arr){
$groupedKeys[$arr][] = $key;
}
foreach($groupedKeys as $key => $groupedKeyArr){
foreach($groupedKeyArr as $groupedKey){
echo $array2[$groupedKey];
}
echo "<br /> ";
}
?>
http://codepad.org/9R9s5lTM
There is a built in function that returns an array with the number of times a value is repeated http://php.net/manual/en/function.array-count-values.php
This is really rough, but a simple way of doing it could be:
<?
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
$prev = $array1[1];
foreach($array1 as $key => $val)
{
if($val != $prev && $key != 1)
{
echo '<br />';
}
echo $array2[$key].' ';
$prev = $val;
}
?>
Example: http://codepad.org/OpLdtStp
This assumes that you're first key is always going to be 1 by the way.
I am providing you a function returns an array with the number of times a value is repeated in an array(as values) and values as the keys. Further task is not difficult.
function check_number_of_times_elements_occur_in_array($a)//returns values of array as keys, associating values being their total occurences in the array
{
$r=array();
foreach($a as $v)
++$r[$v];
return $r;
}
I think this will do for you..
function test($array1,$array2) {
$repeated_values = array_count_values($array1);
foreach($repeated_values as $key => $value){
if($value > 1) {
foreach($array1 as $key1 => $value1){
if($key == $value1){
$repeated_values_keys[] = $key1;
}
}
}
}
$str_top = "";
foreach($repeated_values_keys as $k){
$str_top .= $array2[$k]." ";
}
echo $str_top.'<br/>';
foreach($array2 as $key2 => $value){
if(!in_array($key2,$repeated_values_keys)){
echo $value.'<br/>';
}
}
}

Categories