4

I have two associative arrays. I need to subtract ($price - $tax) to get $total price:

 $price['lunch'] = array("food" => 10, "beer"=> 6, "wine" => 9);
 $price['dinner'] = array("food" => 15, "beer"=> 10, "wine" => 10);

 $tax['lunch'] = array("food" => 2, "beer"=> 3, "wine" => 2);
 $tax['dinner'] = array("food" => 4, "beer"=> 6, "wine" => 4);

Desired result array:

 $result['lunch'] = (['food'] => 8, ['beer'] =>3, ['wine'] => 7 )
 $result['dinner'] = (['food'] => 11, ['beer'] =>4, ['wine'] => 6   )

I'm trying following function and array_map to no avail:

function minus($a, $b) {
    return $a - $b;
 }

      foreach ($price as  $value)
        {
            $big = $value;
            foreach($tax as $v) {
                $small = $v;
        $e[] = array_map("minus",$big, $small);
        }       
        }

With above i get four arrays (first and last one is correct though) so it's not correct. Thanks for any info!

2 Answers 2

5

You could compare using keys instead of array mapping. With a double foreach, you can do any number of meals and food types:

foreach(array_keys($price) as $meal)
{
    foreach(array_keys($price[$meal]) as $type)
    {
        $e[$meal][$type] = $price[$meal][$type] - $tax[$meal][$type];
    }
}

Note, this code doesn't look out for missing items in either the meals or the food types...

Sign up to request clarification or add additional context in comments.

1 Comment

$meal in second foreach is a string not array - i get error - still i'm not sure how this is supposed to work.
3

if the structure of $price and $tax are always equals, you can use the following code:

<?php

$price['lunch'] = array("food" => 10, "beer"=> 6, "wine" => 9);
$price['dinner'] = array("food" => 15, "beer"=> 10, "wine" => 10);

$tax['lunch'] = array("food" => 2, "beer"=> 3, "wine" => 2);
$tax['dinner'] = array("food" => 4, "beer"=> 6, "wine" => 4);

$result = array();
foreach( $price as $what => $value)
{
    foreach( $value as $food => $foodPrice )
    {
        $result[$what][$food] = $foodPrice - $tax[$what][$food];
    }
}

Result:

print_r($result); 

Array
(
    [lunch] => Array
        (
            [food] => 8
            [beer] => 3
            [wine] => 7
        )

    [dinner] => Array
        (
            [food] => 11
            [beer] => 4
            [wine] => 6
        )

)

Comments

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.