Vivil Vivil - 2 months ago 7
PHP Question

If the sum of array 1 exceeds certain number tne further number should store in array 2 next index

I having two arrays , array 1 having certain values. array 1 values should store in the array 2 like the sum of the array1 exceeds 25 it should store in array2's next index


array 1:


$a1=array(10,10,10,10,10,10,10,10,10,10);



array 2:


Array
(
[0] => 10,10,5
[1] => 5,10,10
[2] => 10,10,5
[3] => 5,10,10
)


Here the code i tried but it gets error

$a1=array(10,10,10,10,10,10,10,10,10,10);

$a2=array();

$count=count($a1);


for($i=0;$i<$count;$i++)
{

$a2count=array_sum($a2);

if($a2count>25)
{
$i=$i+1;
$a2[$i]=$a1[$i];
}
else
{
$a2[$i]=$a1[$i];

}
}

print_r($a2);


I don't know what logic to implement and get result

Answer

Here you go: The logic is not so hard. Hope it helps.

   <?php 

   $a1=array(10,10,10,10,10,10,10,10,10,10);

   $a2 = [];
   $a3 = [];

   $m = 0;

   for($i = 0; $i < count($a1); ++$i){      

        $m += $a1[$i];

        if($m > 25){

           $n = $m % 25;

           if(array_sum($a2) != 25){

               $a2[] = $n;

           }


           $a3[] = implode(',', $a2);       

           $a2 = []; 

           $m = $n;

           $a2[] = $n;


         } else{

           $a2[] = $a1[$i];

         }


   }

   $a3[] = implode(',', $a2);

   print_r($a3);

   ?>