php 关联数组相减
我有两个关联数组。我需要减去 ($price - $tax) 以获得 $total 价格:
$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['lunch'] = (['food'] => 8, ['beer'] =>3, ['wine'] => 7 )
$result['dinner'] = (['food'] => 11, ['beer'] =>4, ['wine'] => 6 )
我正在尝试以下函数和 array_map 无济于事:
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);
}
}
上面我得到四个数组(尽管第一个和最后一个是正确的),所以它是不正确。感谢您提供任何信息!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用键而不是数组映射进行比较。使用双 foreach,您可以执行任意数量的餐食和食物类型:
请注意,此代码不会查找餐食或食物类型中缺少的项目...
You could compare using keys instead of array mapping. With a double foreach, you can do any number of meals and food types:
Note, this code doesn't look out for missing items in either the meals or the food types...
如果
$price
和$tax
的结构始终相等,则可以使用以下代码:结果:
if the structure of
$price
and$tax
are always equals, you can use the following code:Result: