在PHP中,我有一个像这样的数组:
$BulkArray[$i]
该阵列具有大量数字(例如,1 => 100,2 => 300,3 => 100,依此类推)。 现在我想在整个数字范围内找到一个等于或小于500的最大连续数。我想写下继承的数量。
例如我有数组
1 => 100, 2 => 300, 3 => 100,
4 => 50, 5 => 50, 6 => 50, 7 => 50, 8 => 50,
9 => 500, 10 => 200, 11 => 100
如你所见,数字1,2和3是500.所以这是第一次继承。
2,3,4,5也是500在一起。 (这个继承(4)比第一个继承(3)更大)
依此类推,那么你将得到最高的继承:3,4,5,6,7,8(继承6个数字),这是350(但是我们搜索的时候低于500米)
现在,我怎么用数组写:
$BulkArray[$i]
,最高的继承是6?
因为6是整个数组中500的最高连续数!
(它用于对特定Carparts进行分类)
答案 0 :(得分:1)
用户的答案" fas M"在这里,几乎没有改进:
<?php //lets call your $BulkArray = $values;
$values=array( 1 => 100, 2 => 300, 3 => 100,
4 => 50, 5 => 50, 6 => 50, 7 => 50, 8 => 50,
9 => 500, 10 => 200, 11 => 100 );
$sum=0; // to sum up until 500
$Vals500=array(); // array to store index with <= 500
$i=0; // index for new aaray that will store keys that made up <= 500
$key1=1; //value to iterate the array defined above
for($key=1; $key <= count($values); $key++){
$sum = $sum + $values[$key]; // get sum of values
if($sum <= 500){ $Vals500[$i][]=$key; } //append all key of sum ==500
if($sum >= 500) { $i++; $key=$key1++; $sum=0; } //check sum then reintialize
//added bigger equal
}
echo count(max($Vals500)); // read out the biggest succession
?>
再次感谢fas M!
答案 1 :(得分:-2)
Click Here或here您可以看到一些内容
<?php //lets call your $BulkArray = $values;
$values=array( 1 => 100, 2 => 300, 3 => 100,
4 => 50, 5 => 50, 6 => 50, 7 => 50, 8 => 50,
9 => 500, 10 => 200, 11 => 100 );
$sum=0; // to sum up until 500
$Vals500=array(); // array to store index with <= 500
$i=0; // index for new aaray that will store keys that made up <= 500
$key1=1; //value to iterate the array defined above
//print_r($values); echo '<br/>';
for($key=1; $key <= count($values); $key++){
$sum = $sum + $values[$key]; // get sum of values
if($sum <= 500){ $Vals500[$i][]=$key; } //append all key of sum ==500
if($sum == 500) { $i++; $key=$key1++; $sum=0; } //check sum then reinitialize values
}
foreach($Vals500 as $val){} //search for second array with many indeces in $Vals500. NB: i fail this place
echo print_r($Vals500);
print 'the highest succession found is '; print_r($Vals500[2]); //
?>
&#13;