how to compare two arrays and find the count of match elements
i have two arrays i.e
$ar1=array("Mobile","shop","software","hardware");
and$arr2=arry("shop","Mobile","shop","software","shop")i want to compare the elements of arr2 to arr1 i.e
foreach($arr2 as $val) { if(in_array($val, $arr1)) { //mycode to insert data into mysql table variable++; // here there should be a variable that must be increamented when ever match found in $arr2 so that it can be saved into another table. } $query="update table set shop='$variable',Mobile='$variable'......."; }
the $variable should be an integer value so that for later use i can use this variable(shop i.e in this example its value should be 3) to find the match.
开发者_运维百科My question is how can i get the variable that will increamented each time match found.Sorry, I don't fully understand the purpose of your code. You can use array_intersect to get common values and array_diff to get the unique values when comparing two arrays.
i want to compare the elements of arr2 to arr1 i.e
Then you are essentially doing the same search for shop three times. It's inefficient. Why not sort and eliminate duplicates first?
Other issues. You are comparing arr2 values with the ones in arr1, which means the number of repetation for "shop" will not be 3 it will be one. Doing the opposite might give you the number of repetation of arr1[1] in arr2 =3.
There are multitude of ways to solve this problem. If efficiency is required,you might wish to sort so you don't have to go beyond a certain point (say s). You can learn to use indexes. Infact the whole datastructure is revolved around these kinds of things - from quick and dirty to efficient.
Not sure I understand the connection between your two arrays. But you can use this to count how many items are in your second array:
$items = array("shop","Mobile","shop","software","shop");
$count = array();
foreach($items as $item)
{
if(isset($count[$item]))
{
$count[$item]++;
}
else
{
$count[$item] = 1;
}
}
print_r($count); // Array ( [shop] => 3 [Mobile] => 1 [software] => 1 )
精彩评论