Home > Backend Development > PHP Tutorial > 2个数组相加,将一个数组写入另一个数组

2个数组相加,将一个数组写入另一个数组

WBOY
Release: 2016-06-23 14:21:05
Original
1033 people have browsed it

已知数组a和数组b:

//数组a:array (  0 =>   array (    'cust_no' => '310F6 1VA5A',    'lotno' => '2X15',    'part_count' => '0',  ),  1 =>   array (    'cust_no' => '310F6 1VA5A',    'lotno' => '2Z25',    'part_count' => '5',  ),)//数组b:array (  0 =>   array (    'cust_no' => '310F6 1VA5A',    'lotno' => '2Z15',    'part_count' => '100',  ),  1 =>   array (    'cust_no' => '310F6 1VA5A',    'lotno' => '3115',    'part_count' => '28',  ),)
Copy after login


把数组b的结果加入数组a,同cust_no,lotno对应的part_count累加。变成这样的结果:
array (  0 =>   array (    'cust_no' => '310F6 1VA5A',    'lotno' => '2X15',    'part_count' => '0',  ),  1 =>   array (    'cust_no' => '310F6 1VA5A',    'lotno' => '2Z15',    'part_count' => '105',  ),  2 =>   array (    'cust_no' => '310F6 1VA5A',    'lotno' => '3115',    'part_count' => '28',  ),)
Copy after login

这样如何做到?需要用哪些数组函数?谢谢!


回复讨论(解决方案)

$t=array();foreach(array_merge($a,$b) as $v){     if(!isset($t[$v['cust_no'].'_'.$v['lotno']])){	     $t[$v['cust_no'].'_'.$v['lotno']]=$v;	 }else{	      $t[$v['cust_no'].'_'.$v['lotno']]['part_count']+=$v['part_count'];	 }	 } print_r(array_values($t));
Copy after login


$v['cust_no'].'_'.$v['lotno']这句是什么意思?

将 cust_no 和 lotno的值组成键判断重复用的

将 cust_no 和 lotno的值组成键判断重复用的
哦,原来可以这样用啊。谢谢了!

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