Home > Backend Development > PHP Tutorial > 求帮忙一下

求帮忙一下

WBOY
Release: 2016-06-23 13:51:53
Original
943 people have browsed it

下面这个表是从数据库拿出来的.应该还可以拿到更多.
id          a                    b
0           10                 2
1           30                 5
2           50                 4

要求从a里拿最高的数,然后用这个数加上b其他的数
例如:   50+2+5=57

如果只用一个array应该怎样做?
或者有更好的解法吗?
(那些数字好象全是string来的)


回复讨论(解决方案)

直接在数据库里面查出来就可以了

select max(concat(a,'-', b)) as a,sum(b) as b  from test
Copy after login

结果:
a b
50-4 11
50-4+11=57

直接 SQL 就是了
select a, (select sum(b) from tbl_name where a< T.a) as b from tbl_nameT
a b
10
30 2
50 7

如果用php写,怎样?
我的想法是把所有a的值放到一个array.
所有b的放到另外一个Array.
然后从a里拿最大值,再加上b里其他的。
有更好的么?

$a = array(10, 30, 50);$b = array(2, 5, 4);$max = max($a);$sum = 0;foreach($a as $i=>$v)  if($v < $max) $sum += $b[$i];echo $max + $sum;
Copy after login

$arr = array(	array(10, 2),	array(30, 5),	array(50, 4));$index = 0;$max = 0;for($i=0,$len=count($arr); $i<$len; $i++){	if($arr[$i][0]>$max){		$max = $arr[$i][0];		$index = $i;	}}$total = $max;for($i=0,$len=count($arr); $i<$len; $i++){	if($i==$index){		continue;	}	$total += $arr[$i][1];}echo $total; // 57
Copy after login

$a = array(10, 30, 50);$b = array(2, 5, 4);$max = max($a);$i = array_search($max, $a);unset($b[$i]);echo $max + array_sum($b); 
Copy after login

Related labels:
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