在 PHP 中比较两个多维数组以求和数据

我有两个数组:


数组A:


$rates = array(

    'apple' = array(

        'red'    => 1.19,

        'green'  => 0.99,

        'yellow' => 0.89

    )

);

数组B:


$cart = array(

    'apple' = array(

        '0'  => red,

        '1'  => green

    )

);

数组 B 是购物车,我需要从数组 A 获取费率。


所以:


苹果 > 红色 >1.19

苹果 > 绿色 >0.99

总共应该是2.18。


这是我尝试过的:


foreach($cart as $key => $arr){

    if(!in_array($key[$arr], $rates)){

        $total += $rates[$key];

    }

}

但这不起作用。


请问我缺少什么?


非常感谢您的帮助。


千巷猫影
浏览 103回答 2
2回答

慕桂英4014372

你有几个问题。首先,您应该检查产品类型 from 是否作为ie$cart中的键存在$ratesif(!in_array($key[$arr], $rates)){应该:if (isset($rates[$key])) {其次,一旦确定键确实存在于中$rates,则需要迭代中的每个值$arr以获取其价格$rates(使用空合并运算符来避免值不在费率数组中的问题):$total = 0;foreach ($cart as $key => $arr) {    if (isset($rates[$key])) {        foreach ($arr as $value) {            $total += $rates[$key][$value] ?? 0;        }    }}echo $total;输出:2.183v4l.org 上的演示

偶然的你

<?php$rates = array(&nbsp; &nbsp; 'apple' => array(&nbsp; &nbsp; &nbsp; &nbsp; 'red'&nbsp; &nbsp; => 1.19,&nbsp; &nbsp; &nbsp; &nbsp; 'green'&nbsp; => 0.99,&nbsp; &nbsp; &nbsp; &nbsp; 'yellow' => 0.89&nbsp; &nbsp; ));$cart = array(&nbsp; &nbsp; 'apple' => array(&nbsp; &nbsp; &nbsp; &nbsp; '0'&nbsp; => 'red',&nbsp; &nbsp; &nbsp; &nbsp; '1'&nbsp; => 'green'&nbsp; &nbsp; ));$total = 0;foreach($cart as $type => $items) {&nbsp; &nbsp; if(array_key_exists($type, $rates)) {&nbsp; &nbsp; &nbsp; &nbsp; foreach($items as $item) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(array_key_exists($item, $rates[$type])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $total += $rates[$type][$item];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}echo $total;?>
打开App,查看更多内容
随时随地看视频慕课网APP