计算数组中价格字段的总和

发布于 2024-09-18 03:53:55 字数 250 浏览 1 评论 0原文

( [0] => Array 
( [0] => Array ( 
[0] => Array ( [price] => 76  ) 
[1] => Array ( [price] => 200  ) 
[2] => Array ( [price] => 500  ) 
[3] => Array ( [price] => 67  ) 

有没有一种干净的方法来计算所有这些价格

( [0] => Array 
( [0] => Array ( 
[0] => Array ( [price] => 76  ) 
[1] => Array ( [price] => 200  ) 
[2] => Array ( [price] => 500  ) 
[3] => Array ( [price] => 67  ) 

is there a clean way to calculate all these prices

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怀里藏娇 2024-09-25 03:53:55

array_sum() 手册中进行一些挖掘(在用户部分阅读)我遇到了这个功能:

function array_sum_key( $arr, $index = null ){
    if(!is_array( $arr ) || sizeof( $arr ) < 1){
        return 0;
    }
    $ret = 0;
    foreach( $arr as $id => $data ){
        if( isset( $index )  ){
            $ret += (isset( $data[$index] )) ? $data[$index] : 0;
        }else{
            $ret += $data;
        }
    }
    return $ret;
}

鉴于手册中的注释,我将如何想象您使用它

$sum = array_sum_key($products[0][0], 'price');

希望它对您有用,因为这应该是一个简单的解决方案:)

Doing some digging at the array_sum() manual (reading in the user section) I came across this function:

function array_sum_key( $arr, $index = null ){
    if(!is_array( $arr ) || sizeof( $arr ) < 1){
        return 0;
    }
    $ret = 0;
    foreach( $arr as $id => $data ){
        if( isset( $index )  ){
            $ret += (isset( $data[$index] )) ? $data[$index] : 0;
        }else{
            $ret += $data;
        }
    }
    return $ret;
}

How I would in-vision you using it, given the remarks at the manual

$sum = array_sum_key($products[0][0], 'price');

Hopefully it works out for you, as that should be an easy solution :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文