读书人

数组加减有关问题

发布时间: 2013-09-05 16:02:07 作者: rapoo

数组加减问题
已知数组a和b。


//数组a:
array (
0 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2X15',
'part_count' => '32',
),
1 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2Z25',
'part_count' => '32',
),
)

//数组b:

array (
0 =>
array (
'cust_no' => '310F6 1VA5A',
'total' => '48',
),
)


数组a cust_no为310F6 1VA5A时,对应的总量是32+32=64,数组b cust_no为310F6 1VA5A时对应的总量是48。
想求得数组b总量为48时,对应数组a中的哪些内容?数组a剩余的结果是多少?

以这个例子来说,
得到数组a的结果:

//数组a:
array (
0 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2X15',
'part_count' => '32',
),
1 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2Z25',
'part_count' => '16',
),
)

剩余数组a的结果:

//数组a:
array (
0 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2X15',
'part_count' => '0',
),
1 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2Z25',
'part_count' => '16',
),
)


如何能得到这样的结果?
------解决方案--------------------


你之前不是问过这个问题了么?

如果你要对类似数组做很多纵向(column)计算的话,我建议你不如做个行列转换,思路就开阔多了
大不了计算完成后再一次行列转换换回来就是了
[解决办法]
不是数据库,就是php的数组,把一维和二维的key对调
$a[行][列] 转换成 $a[列][行] 而已
这样就可以把 $a[某列] 作为一个一维数组,做加减,交并差,累计都很方便

我记得以前发过的
[解决办法]

//数组a:
$a = array (
0 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2X15',
'part_count' => '32',
),
1 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2Z25',
'part_count' => '32',
),
);

//数组b:

$b = array (
0 =>
array (
'cust_no' => '310F6 1VA5A',
'total' => '48',
),
);

foreach($b as $source) {
$num = $source['total'];
foreach($a as $i=>$dest) {
if($num == 0) break;
if($dest['cust_no'] != $source['cust_no']) continue;
if($num >= $dest['part_count']) {
$num -= $dest['part_count'];
$res[] = $dest;
$a[$i]['part_count'] = 0;
}else {
$dest['part_count'] = $num;
$res[] = $dest;
$a[$i]['part_count'] -= $num;
$num = 0;
}
}
}
var_export($res);
var_export($a);
array (
0 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2X15',
'part_count' => '32',
),
1 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2Z25',
'part_count' => 16,


),
)


array (
0 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2X15',
'part_count' => 0,
),
1 =>
array (
'cust_no' => '310F6 1VA5A',
'lotno' => '2Z25',
'part_count' => 16,
),
)

读书人网 >PHP

热点推荐