How do I subtract arrays

1
array_intersect_ukey($result1, $result2, 'key_compare_func2') // primeiro array
array_intersect_ukey($result2, $result1, 'key_compare_func2') // segundo array

Result:

Array
(
    [bife] => 3
)
Array
(
    [bife] => 2
)

Desired:

Array
(
    [bife] => 1
)
    
asked by anonymous 17.09.2014 / 03:52

2 answers

4

Here is a function that "merges" arrays, subtracting items with equal keys in both:

function subtrai_array( $arr1, $arr2 ) {
   foreach ( $arr2 as $chave => $valor ) {
       if( array_key_exists( $chave, $arr1 ) ) {
           $arr1[$chave] = $arr1[$chave] - $valor;
      } else {
         $arr1[$chave] = -$valor;
      }
   }
   return $arr1;
}

See working at IDEONE .

    
17.09.2014 / 05:10
0

Based on the @Bacco example, I'll propose another way using array_merge_recursive . Basically it will combine the 2 arrays and generate an array of 2 keys when there is a match, then a loop with subtraction.

The example considers 2 arrays (stock and sale), where sales items are expressly in stock - only sells that are in stock.

$result = array_merge_recursive($a1, $a2);

foreach ($result as $key => $value )
{
    if( is_array( $value ) )
    {
        $array[ $key ] = ($value[0] - $value[1]);
    }
    else
    {
        $array[ $key ] = $value;
    }
}

Example in ideone , output:

+------------+-----------+-----------+-----------+-----------+
| estoque    | produto.1 | produto.2 | produto.3 | produto.4 |
| quantidade | 2         | 5         | 3         | 9         |
+------------+-----------+-----------+-----------+-----------+
| venda      | produto.1 |           | produto.3 |           |
| quantidade | 1         |           | 2         |           |
+------------+-----------+-----------+-----------+-----------+
| resultado  | produto.1 | produto.2 | produto.3 | produto.4 |
| quantidade | 1         | 5         | 1         | 9         |
+------------+-----------+-----------+-----------+-----------+
    
17.09.2014 / 05:53