使用PHP向数组添加一个数字

时间:2016-06-22 12:21:49

标签: php arrays

我有一个测验,来自MySQL DB的问题。你能帮我解决一下吗?

我想将(+1)添加到数组中的特定值。

    <input id="subjectid" name="subjectid[]" value="2" type="checkbox">maths
    <input id="subjectid" name="subjectid[]" value="3" type="checkbox">science
    <input id="subjectid" name="subjectid[]" value="5" type="checkbox">social science
    <input id="subjectid" name="subjectid[]" value="9" type="checkbox">english
    <input id="subjectid" name="subjectid[]" value="11" type="checkbox">computer
    <input id="subjectid" name="subjectid[]" value="14" type="checkbox">ME

<?php 
$sid=$_POST['subjectid'];

if(!empty($sid)) {
$newids = array();
    foreach($sid as $check) {
            $newids[]=$check;

    }
}

$totalcount=count($newids);
$totalquestions='40';
$remainder=40 % $totalcount;
$number=explode('.',(40 / $totalcount));
$answer=$number[0];


if($remainder=='0'){
$newcount=$totalquestions/$totalcount;
$a = array_fill_keys($newids, $newcount);
}else{
$a = array_fill_keys($newids, $answer);
}



?>

case 1)

if i select 5 checkboxes subjects, quetions takes from db correct 40/5=8


Array
(
    [2] => 8
    [3] => 8
    [5] => 8
    [9] => 8
    [11] => 8
)

array=array('2'=>'8','3'=>'8','5'=>'8','9'=>'8','11'=>'8');

foreach($array as $k=>$v)
{
  select * from where sujectid=$k rand() limit $v
}

--------------------------------------------------------------------------------------
case 2)

if i select 6 checkboxes subjects, quetions takes from db correct 40/6, 6*6=36, remainaing 4 questions, 36+4=40

Array
(
    [2] => 6+1
    [3] => 6+1
    [5] => 6+1
    [9] => 6+1
    [11] => 6
    [14] => 6
)

$array=array('2'=>'7','3'=>'7','5'=>'7','9'=>'7','11'=>'6','14'=>'6');

foreach($array as $k=>$v)
{
  select * from where sujectid=$k rand() limit $v
}

1 个答案:

答案 0 :(得分:1)

像这样的东西(增加前4个数组值):

$i = 0;
foreach($arr as $k => $v) {
  if (++$i > 4) break; // affect only first 4 elements
  $arr[$k]++;          // increment by1
}