Jarod
Jarod

Reputation: 199

efficient way of php array compare

Here's the two array to be compared.

array_a(
[0] => array('userid' => aaa, 'created_time' => XXXX,),
[1] => array('userid' => bbb, 'created_time' => XXXX,),
[2] => array('userid' => ccc, 'created_time' => XXXX,)
)


array_b(
[0] => array('userid' => aaa, 'created_time' => XXXX,),
[1] => array('userid' => ccc, 'created_time' => XXXX,),
[2] => array('userid' => ddd, 'created_time' => XXXX,)
)

I wanna retrieve all the element that match the following conditions: array_a's userid is in array_b and array_a's created_time is newer than array_b's

I use the following code to do this,but it will take a long time if the array is huge.

for array_a{
  for array_b{
    if (a[user_id] = b[user_id] && a[created_time] > b[created_time]) {
      //target got
    }
  }
}

Is there any way to do this logic efficiently?

Thanks for answering. the IDs are unique. How to convert array_a( [0] => array('userid' => aaa, 'created_time' => XXXX,), [1] => array('userid' => bbb, 'created_time' => XXXX,), )

to the form array(aaa=>XXXX,bbb=>XXXX) ?

Upvotes: 0

Views: 329

Answers (4)

miro
miro

Reputation: 780

foreach($array_a as $arr)  
  $tmp[$arr['userid']] = $arr['created_time']; //rebulding first array

foreach($array_b as $arr)
  if(isset($tmp[$arr['userid']]) && $arr['created_time'] < $tmp[$arr['userid']]){
    //target  
  } 

as first you have to rebuild one of your array to structure suitable for next step, where you will searching for items meeting your condition. this solution should be better than yours because it has much smaller count of loops (2*n instead of n^2)

Upvotes: 0

Jack
Jack

Reputation: 5768

$b_index = 0;
for ($a_index = 0; $a_index < count($a); $a_index++)
{
    if ($a[$a_index]['userid'] == $b[$b_index]['userid'])
    {
        if ($a[$a_index]['created_time'] >= $b[$b_index]['created_time']) 
            $array[] = $a[$a_index];
        $b_index++;
    }
}

If the userid's are both sorted in the same order, you don't need to compared each userid in a with each userid in b to look for match. This should be less comparisons at least.

Upvotes: 0

symcbean
symcbean

Reputation: 48357

Sort both arrays by user id then created time. Order is still O(N^2) but the number of comparisons is greatly reduced. However since you're looking for an explicit match on userid, then converting the arrays to array('aaa'=>array(0=>'created_time', 1=>'created_time'...)...) then getting the value of array_intersect(array_a, array_b) will give you all the common user ids.

Upvotes: 0

Wander Nauta
Wander Nauta

Reputation: 19615

You could consider using the userid of each element as the array key. This allows you to look up the correct item in B in O(1) time.

Upvotes: 0

Related Questions