JoeP
JoeP

Reputation: 876

PHP Compare two nested arrays to get a new array

I am trying to subtract parts of one nested array from another, but I'm having difficulty specifying the parts that I want to subtract as both values are numbers.

My arrays are, for example:

Array ( [0] => Array ( [id] => 43 [quantity] => 4 ) ) 
Array ( [0] => Array ( [id] => 43 [quantity] => 2 ) )

And after the subtraction I want the Result to be:

Array ( [0] => Array ( [id] => 43 [quantity] => 2 ) )

I'm using the following code to perform the subtraction, but I can't stop it from subtracting the id from itself:

foreach(array_keys($arrayA) as $id)
{
    foreach(array_keys($arrayA[$id]) as $type)
    {
        $newArray[$id][$type] = $arrayA[$id][$type] - $arrayB[$id][$type];
    }
}

print_r($newArray);

Could someone please tell me how I can just effect the [quantity] part of the array, without changing the [id]? With the code as it is I get:

Array ( [0] => Array ( [id] => 0 [quantity] => 2 ) )

Thanks in advance.

Upvotes: 0

Views: 100

Answers (1)

Xevelion
Xevelion

Reputation: 869

$ar1 = array(0 => array('id' => 43, 'quantity' => 4));
$ar2 = array(0 => array('id' => 43, 'quantity' => 2));
$new_array = array();

foreach($ar1 as $key => $value)
{
    $new_array[$key] = array('id' => $value['id'], 'quantity' => ($value['quantity'] - $ar2[$key]['quantity']));
}

Array 
( 
    [0] => Array 
        ( 
            [id] => 43 
            [quantity] => 2 
        ) 
)

Upvotes: 2

Related Questions