具有特定键和条件的 PHP 数组总和

Array

(

    [6254] => Array

        (

            [check] => on

            [quantity] => 2

            [name] => Testing product_special One Size

            [total] => 66.0000

            [price] => 33.0000

        )


    [6255] => Array

        (

            [check] => on

            [quantity] => 1

            [name] => Testing card

            [total] => 80.85

            [price] => 33.0000

        )


)

以上是我的阵列。


我的代码


foreach($value as $key2 => $value2){

    $name = preg_replace('/\s+/', '', $key);

    echo "<pre>";

    // print_r(array_sum(array_column($value, 'price')));

    print_r($value);

    echo "</pre>";

    exit;

}

想问一下,如何“具体”加价?试过


$totalprice += $value['price'];

不管用


array_sum(array_column($value, 'price')) < 此代码解决了我的问题


但是有一个新问题,如果需要检查“条件”怎么办


如果 "check" = on 只能求和,如果没有 "check" 忽略数组


DIEA
浏览 81回答 2
2回答

慕姐8265434

如果数组存储在 中$value,您应该使用$totalprice += $value2['price'];,因为$value2它本身就是一个数组。

四季花海

您需要在 $yourRegex 变量中指定正则表达式模式。$total= 0;foreach($value as $key => $value){&nbsp; &nbsp; $yourRegex = '/\s+/';&nbsp; &nbsp; if(preg_match($yourRegex, '', $key)) {&nbsp; &nbsp; &nbsp; &nbsp; $total+= $value['price'];&nbsp; &nbsp; }}echo $total;
打开App,查看更多内容
随时随地看视频慕课网APP