亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對 php 數組進行分組的最佳方法是什么?

對 php 數組進行分組的最佳方法是什么?

PHP
烙印99 2023-10-15 16:44:23
例如,我有這個數組:$bills = array(                 array("bill_id"=>"1", "product_id"=>"1", "total"=>"10"),                 array("bill_id"=>"2", "product_id"=>"2", "total"=>"20"),                 array("bill_id"=>"3", "product_id"=>"1", "total"=>"30"),                 array("bill_id"=>"4", "product_id"=>"1", "total"=>"40"),                 array("bill_id"=>"5", "product_id"=>"2", "total"=>"50")            );我們需要將每個產品的總計添加到一個數組中,即從上面的數組生成以下數組的最佳干凈快速方法是什么: $products = array(                array("product_id"=>"1", "total"=>"80"),                array("product_id"=>"2", "total"=>"70")            );
查看完整描述

2 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

求和的最快方法是索引數組,像這樣


$products = array();


foreach ($bills as $bill) {

    $key = $bill['product_id'];

    if (isset($products[$key])) {

        $products[$key]['total'] += $bill['total'];

    } else {

        $products[$key] = $bill;

    }

}


var_dump($products);

輸出


array(2) {

  [1]=>

  array(3) {

    ["bill_id"]=>

    string(1) "1"

    ["product_id"]=>

    string(1) "1"

    ["total"]=>

    int(80)

  }

  [2]=>

  array(3) {

    ["bill_id"]=>

    string(1) "2"

    ["product_id"]=>

    string(1) "2"

    ["total"]=>

    int(70)

  }

}

瀏覽發票清單


foreach($products as $key=>$bill) {

    var_dump($bill);

}


查看完整回答
反對 回復 2023-10-15
?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

最簡單的方法是單遍循環。


$byProduct = [];


foreach($bills as $bill)

{

    $key = $bill['product_id'];

    if (!isset($byProduct[$key])) {

        $byProduct[$key] = [

            'product_id' => $key,

            'total' => 0

        ];

    }


    $byProduct[$key]['total'] += $bill['total'];

}

結果var_dump($byProduct):


array(2) {

  [1] =>

  array(2) {

    'product_id' =>

    string(1) "1"

    'total' =>

    int(80)

  }

  [2] =>

  array(2) {

    'product_id' =>

    string(1) "2"

    'total' =>

    int(70)

  }

}

另一種方法是使用array_walk,但在復雜性方面幾乎相同:


$byProduct = [];


array_walk($bills, function(&$bill) use (&$byProduct) {

    $key = $bill['product_id'];

    if (!isset($byProduct[$key])) {

        $byProduct[$key] = [

            'product_id' => $key,

            'total' => 0

        ];

    }


    $byProduct[$key]['total'] += $bill['total'];

});


查看完整回答
反對 回復 2023-10-15
  • 2 回答
  • 0 關注
  • 131 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號