-2

Assume I have two arrays $array1 :

array (size=3)
  0 =>
    array (size=5)
      'id' => int 16
      'project_id' => string '37' (length=2)
      'description' => string 'Guitar' (length=6)
      'qty' => int 87
      'uom' => string 'Units' (length=5)

  1 =>
    array (size=5)
      'id' => int 17
      'project_id' => string '37' (length=2)
      'description' => string 'Drums' (length=5)
      'qty' => int 889
      'uom' => string 'Drum' (length=4)

  2 =>
    array (size=5)
      'id' => int 13
      'project_id' => string '37' (length=2)
      'description' => string 'Bump' (length=4)
      'qty' => int 76
      'uom' => string 'Units' (length=5)

and $array2 :

array (size=2)
  0 =>
    array (size=3)
      'id' => int 17
      'qty' => int 800
  1 =>
    array (size=3)
      'id' => int 16
      'qty' => int 87

I need some help:

  • merge above arrays by id and do subtraction of qty values
  • check if qty values less than or equal to 0 do not include in $result.

so the final $result would be:

array (size=2)
  0 =>
    array (size=5)
      'id' => int 17
      'project_id' => string '37' (length=2)
      'description' => string 'Drums' (length=5)
      'qty' => int 89
      'uom' => string 'Drum' (length=4)

  1 =>
    array (size=5)
      'id' => int 13
      'project_id' => string '37' (length=2)
      'description' => string 'Bump' (length=4)
      'qty' => int 76
      'uom' => string 'Units' (length=5)

Any help would be appreciated, thanks.

4
  • Hi, what have you tried? Commented Sep 13, 2015 at 19:49
  • Does array 1 have an equal number of values when compared to array 2? You have 3 in array 1 and 2 in array 2, is the data like this too? Commented Sep 13, 2015 at 19:56
  • possible duplicate of PHP: Merge 2 Multidimensional Arrays Commented Sep 13, 2015 at 19:59
  • @IndigoIdentity sorry if can't include what have I done, because what I tried nothing approach to solve this problem. Commented Sep 13, 2015 at 20:36

1 Answer 1

2

Try this:

foreach($array1 as $a) {
    $match = false;
    foreach($array2 as $b) {
        if ($a['id'] == $b['id']) {
            $match = true;
            if (($a['qty'] - $b['qty']) > 0) {
                $a['qty'] -= $b['qty'];
                $result[] = $a;
                break;
            }
        }
    }
    if(!$match) $result[] = $a; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried over 4 hours to solving this problem, thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.