php兑现数组的合并

WBOY
Release: 2016-06-13 13:03:14
Original
903 people have browsed it

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;
	}
Copy after login
Related labels:
amp
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template