php - why this is not the array I need? -


i have array $num_arr ,so want new array it's sum smaller 10,so write code this,

$num_arr=array(1,3,6,5,4,2,7,9,5,3,6,2,4,7); $sum=0; for($i=0;$i<=count($num_arr);$i++){     $sum+=$num_arr[$i];     $k++;     if($sum>=10){         $need_arr[]=array_slice($num_arr,0,$k);         array_splice($num_arr,0, $k);            $k=0;         $sum=0;     }        } 

the result $need_arr not right,that why , how can right array this: array(array(1,3,6),array(5,4),array(2,7),array(9),...)?

implemented "oneliner" fun:

$num_arr=array(1,3,6,5,4,2,7,9,5,3,6,2,4,7);  $result = array_reduce($num_arr, function($result, $curr) {     if (!count($result)) {         $result[] = array();     }     $last =& $result[count($result) - 1];      if (array_sum($last) + $curr > 10) {         $result[] = array($curr);     } else {         $last[] = $curr;     }      return $result; }, array());  var_dump($result); 

online demo: http://ideone.com/afvmkp


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -