欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 分享一个php数组合并的实例代码,学习下php中实现数组合并的方法,有需要的朋友做个参考。 最近做一个报表,要求若某几项相同就合并这几行,并将数字项相加显示。 首先,考虑遍历数组,拿出数组的最
欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入
分享一个php数组合并的实例代码,学习下php中实现数组合并的方法,有需要的朋友做个参考。
最近做一个报表,要求若某几项相同就合并这几行,并将数字项相加显示。
首先,考虑遍历数组,拿出数组的最后一项跟其它项比较,若符合条件则做合并操作并删除该项。
但是实际运行,发现执行3次后就不执行了,而这时的数组长度是6.一直没搞懂为什么不继续执行了。
数组是采用&引用删除的,删除项确影响到了原数组的。
既然删除会影响遍历,那就不删除,而是将该项的值设置为空。
问题就解决了,最后用array_filter过滤下空值即可。
php数组合并代码:
代码示例:
//合并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;
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment