Compare all value of two array in one foreach - php

I've 2 array in php
$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');
This is a result of select query wrote in codeigniter. so that is associative array. This is 2 query result one is for user list and second is for invited user list. I want check in user list which user is invited. So that I want to compare that array
foreach ($array1 as $key => $value) {
if($array2[$key]->invite_user_id==$value->user_id) {
echo "Matched";
}
}
but it compare only 2 value of array1 with array2 3rd value is not compare. How it could compare all value of array1 and array2 in above foreach loop

I found that answer
$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');
$invitationset = [];
foreach ($array2 as $invite) {
$invitationset[$invite->invite_user_id] = $invite->invite_user_id;
}
foreach ($array1 as $key => $value) {
if(isset($invitationset[$value->user_id])){
if($invitationset[$value->id]==$value->user_id){
echo "Matched";
}
}
}

In your assoc arrays you have dublicate keys. So if you use:
print_r( $array1 );
You'll see that your array only contains the last entry:
Array ( [user_id] => 3 )
I think that is not what you have expected. So you have to use different keys like that:
$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');
Or you even dont use assoc arrays because it is obsolete in your example but never mind:
$user_ids = array('1','2','3');
$invited_user_ids = array('1','3');
You can compare your assoc arrays like that:
$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');
foreach ($array1 as $user_id) {
if( in_array( $user_id, $array2 ) ) {
echo "Matched id: $user_id";
}
}

Related

How to compare LARGE Multidimensional arrays in PHP

I searched and searched over this foro and this question is not in it, please help me with this if someone can.
I have two LARGE multidimensional arrays with the following formats
$arr1 = array( array (n1,n2,..,n=5), array (n1,n2,..,n=5), n-arrays (n1,...,n5) )
Note: the subarrays of arr1 have 5 numbers each .
$arr2 = array( array (n1,n2,..,n=4), array (n1,n2,..,n=4), n-arrays (n1,...,n4) )
Note: the subarrays of arr2 have 4 numbers each .
Now, I need to remove from arr1 the sub-arrays that include the sub-arrays in arr2. Please, see below an example:
With this two arrays:
$arr1 = array(array(1,2,6,8,10), array(2,4,6,8,10), array(20,40,60,80,100));
$arr2 = array(array(1,6,8,10), array(200,400,600,800));
The code must return:
$ret = array(array(2,4,6,8,10), array(20,40,60,80,100));
Because the numbers of (1,6,8,10) are in (1,2,6,8,10)
This is that code that I'm using now, and it works, but for a limmited number of data.... I think I need something more efficient
foreach ($arr1 as $key => $a ) {
foreach ($arr2 as $a2) {
if ( count(array_diff($a, $a2)) == 1 ) {
unset($arr1[$key]); break; }
}
}
}
You can use empty() to check if all elements were removed during array_diff()
foreach ($arr1 as $key => $v1) {
foreach ($arr2 as $v2) {
if (empty(array_diff($v2, $v1))) {
unset($arr1[$key]);
break;
}
}
}
print($arr1);
Or if your sticking with count(), you can change it to something like
if ( count(array_diff($a2, $a) < 1)) { // array_diff has the $a2 first
unset($arr1[$key]); break;
}

Search value in multidimensional array and sum the value

I'm trying to do a function that search a value inside a multidimensional array and adding up the value from the findings. The array is as below
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
I'm trying to search all 'MY106782' inside the "SponsorID" array, get the 'totalSales' value when found and add the values if the is multiple records
Since your array is a key value pair arrays, you have to determine which key are you looking for. Check this:
$sponsor_id = "MY106782";
$total_sales = 0;
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
foreach($arr as $values) {
if($values["SponsorID"] == $sponsor_id) {
$total_sales += (float)$values["totalSales"];
}
}
echo $sponsor_id . " - " . $total_sales;
try to something like this
$i = 0;
foreach ($arr as $key => $value) {
if ($value['SponsorID'] == 'MY106782') {
$i++;
}
}
Output: 2
You can use below script if key is exist only once time in a array.
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
$key_to_check = 'MY157278';
if (array_key_exists($key_to_check, $arr)) {
echo $arr[$key_to_check]['totalSales'];
}else{
echo "key not found."
}

How to create an array of arrays from another array filtering it by a specific key of the subarrays?

I have following array of arrays:
$array = [
[A,a,1,i],
[B,b,2,ii],
[C,c,3,iii],
[D,d,4,iv],
[E,e,5,v]
];
From this one, I would like to create another array where the values are extract only if the value of third key of each subarray is, for example, greater than 3.
I thought in something like that:
if $array['2'] > 3){
$new_array[] = [$array['0'],$array['2'],$array['3']];
}
So in the end we would have following new array (note that first keys of the subarrays were eliminate in the new array):
$new_array = [
[D,4,iv],
[E,5,v]
];
In general, I think it should be made with foreach, but on account of my descripted problem I have no idea how I could do this. Here is what I've tried:
foreach($array as $value){
foreach($value as $k => $v){
if($k['2'] > 3){
$new_array[] = [$v['0'], $v['2'], $v['3']];
}
}
}
But probably there's a native function of PHP that can handle it, isn't there?
Many thanks for your help!!!
Suggest you to use array_map() & array_filter(). Example:
$array = [
['A','a',1,'i'],
['B','b',2,'ii'],
['C','c',3,'iii'],
['D','d',4,'iv'],
['E','e',5,'v']
];
$newArr = array_filter(array_map(function($v){
if($v[2] > 3) return [$v[0], $v[2], $v[3]];
}, $array));
print '<pre>';
print_r($newArr);
print '</pre>';
Reference:
array_map()
array_filter()
In the first foreach, $v is the array you want to test and copy.
You want to test $v[2] and check if it match your condition.
$new_array = [];
foreach($array as $v) {
if($v[2] > 3) {
$new_array[] = [$v[0], $v[2], $v[3]];
}
}

Display array_key from PHP array?

Here I am Having an Issue:
I have two arrays like the following:
$array1 = array('1','2','1','3','1');
$array2 = array('1','2','3'); // Unique $array1 values
with array2 values i need all keys of an array1
Expected Output Is:
1 => 0,2,4
2 => 1
3 => 3
here it indicates array2 value =>array1 keys
Just use a loop:
$result = array();
foreach ($array1 as $index => $value) {
$result[$value][] = $index;
}
If you pass array_keys a 2nd parameter, it'll give you all the keys with that value.
So, just loop through $array2 and get the keys from $array1.
$result = array();
foreach($array2 as $val){
$result[$val] = array_keys($array1, $val);
}
The following code will do the job. It will create a result array in which the attribute val will contain the value that is searched in array and keys attribute will be an array that contains the found keys. Based on your values following is an example:
$array1 =array('1','2','1','3','1');
$array2 =array('1','2','3');
$results = array();
foreach ($array2 as $key2=>$val2) {
$result = array();
foreach ($array1 as $key1=>$val1 ) {
if ($val2 == $val1) {
array_push($result,$key1);
}
}
array_push($results,array("val"=>$val2,keys=>$result ));
}
echo json_encode($results);
The result will be:
[{"val":"1","keys":[0,2,4]},
{"val":"2","keys":[1]},
{"val":"3","keys":[3]}]

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