很多站长朋友们都不太清楚php随机数字相加,今天小编就来给大家整理php随机数字相加,希望对各位有所帮助,具体内容如下:
本文目录一览: 1、 PHP数组计算 如下数组$arr,求方法随机对数组的值相加,求和为指定值:如(690),输出:405+180+105=690 2、 在PHP网页中怎么编写代码实现数字每天自动加10! 3、 用PHP编任意取五个随机数的总和、平均数。在线等 PHP数组计算 如下数组$arr,求方法随机对数组的值相加,求和为指定值:如(690),输出:405+180+105=690<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
/**
* 根据某个值对数组中的元素进行分组
*/
function getGroupBySum($arr, $sum) {
$len = count($arr);
$result = [];
// for 1
for($i = 0; $i < $len; $i++) {
// for 2
for($j = 1; $j < $len - $i; $j++) {
$tmp = array_slice($arr, $i+1, $j);
array_unshift($tmp, $arr[$i]);
if(array_sum($tmp) == $sum) {
$result[] = $tmp;
}
}
//for 3
for($k = $i + 1; $k < $len; $k++) {
if(($arr[$i] + $arr[$k]) == $sum) {
$result[] = [$arr[$i], $arr[$k]];
}
}
}
return $result;
}
print_r(getGroupBySum($arr, 10));
打印结果:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[1] => Array
(
[0] => 1
[1] => 9
)
[2] => Array
(
[0] => 2
[1] => 8
)
[3] => Array
(
[0] => 3
[1] => 7
)
[4] => Array
(
[0] => 4
[1] => 6
)
)
函数getGroupBySum的算法解释:
我只能解释到这里了,剩下的只可意会。
---------------------------2017/2/16/19:45--------------
下班回去的途中,仔细思考了一下,我上面的函数还没有找到 1、2、7与1、3、6等等,所以它是错的。
我对题目的理解是:数组中任意个元素的和等于某个值,把这些元素组合找出来。
如果没有理解错题意的话,我写不出来这种算法,组合太多了。
在PHP网页中怎么编写代码实现数字每天自动加10!如果只是网页上显示,不需要存储人数据库
则设置初始值$count 还有初始日期$date,
假设$count=10,$date='2015-07-18';
然后进行操作,方法和上面大同小异
$now = strtotime(date('Y-m-d', time()));
if($now > strtotime($date))
{
$add = intval(($now-strtotime($date))/(24*3600));
$count += 10*$add;
}
可以将其封装成函数
function count($count,$date){
$now = strtotime(date('Y-m-d', time()));
if($now > strtotime($date))
{
$add = intval(($now-strtotime($date))/(24*3600));
$count += 10*$add;
}
return $count;
}
如果要加随机数那么就需要加上random函数,而且需要存储用来判定的$date,可以用cookies存储也可以用session存储
用PHP编任意取五个随机数的总和、平均数。在线等srand(microtime()*$_GET['time']);//设置随机数的种子
$sum=0;
$i=0;
while(++$i<=5)$sum+=rand(1,100);//取1-100的随机数
echo '总和:'.$sum.'<br />';
echo '平均数:'.($sum/5).'<br />';
关于php随机数字相加的介绍到此就结束了,不知道本篇文章是否对您有帮助呢?如果你还想了解更多此类信息,记得收藏关注本站,我们会不定期更新哦。
查看更多关于php随机数字相加 php随机数组的详细内容...