php兌現數組的合并

來源:互聯網
上載者:User
php實現數組的合并
最近做一個報表,要求若某幾項相同就合并這幾行,並將數字項相加顯示。

首先考慮遍曆數組,拿出數組的最後一項跟其它項比較,若符合條件則做合併作業並刪除該項。

但是實際運行,發現執行3次後就不執行了,而這時的數組長度是6.一直沒搞懂為什麼不繼續執行了。數組是採用&引用刪除的,刪除項確影響到了原數組的。


後來想到一個辦法,既然刪除會影響遍曆,那就不刪除,而是將該項的值設定為空白。問題就解決了,最後用array_filter過濾下空值就可以了。

代碼如下

//合并itemsearch的結果private function mergeList(&$arr){$data = array();$n = &$arr;foreach ($n as $key => $value) {if(!$value) continue;array_push($data,$this->getItem($value,$n));}return array_filter($data);}private function getItem(&$item,&$arr){foreach ($arr as $key => $value) {if(!$value) {continue;};if($item["itemTypeName"] == $value["itemTypeName"]&& $item["weight"] == $value["weight"]&& $item["type"] == $value["type"]){if($item["itemTypeId"] == $value["itemTypeId"]&& $item["warehouseId"] == $value["warehouseId"]){continue;}else{$item["stockIn"] += $value["stockIn"];$item["remain"] += $value["remain"];$item["stockOut"] += $value["stockOut"];$item["stockIn"] = sprintf("%.4f",$item["stockIn"]);$item["remain"] = sprintf("%.4f",$item["remain"]);$item["stockOut"] = sprintf("%.4f",$item["stockOut"]);$arr[$key] = "";}}}return $item;}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.