0

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.

1 Answer 1

2
$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 
        ) 
)
Sign up to request clarification or add additional context in comments.

2 Comments

Aaagh. Just beat me to it!
That's basically what I started with, and moved on to the other way of trying it because this way didn't seem to work, but this is working perfectly now so I must have made a mistake with my original. Thank you! :)

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.