将 var 的较大序列添加到 CSV 文件

问题描述 投票:0回答:1

我正在尝试将所有值作为序列添加到 csv 文件中以对其进行分析。但我需要将它作为一个序列分开。

主要目的只是找到更大的序列并添加到csv文件中。

 <?php 
    
    $stake = 500;
    
    
    $times_to_run = 10000;
    
    $i = 0;
    
    
    while ($i++ < $times_to_run)
    {
    $arr = array(1, 2, 3, 4, 5, 6, 7);
    
    $result = rand(0, 10);
    if (in_array($result, $arr)) { 
        echo $stake++."</br>"; 
        echo "Win Result: ".$result."</br></br>";
        
    } else { 
        echo $stake--."</br>";
        //find the larger sequence of this var and save to csv
        
    
    $array = explode(' ', $stake);  
        $fp = fopen('file.csv', 'w');
    
    
        fputcsv($fp, $array);
    
    
    fclose($fp);
        
    } 
    }
    ?>

这就是我需要的,在 while 循环中找到该 var 出现的最长序列并保存到 csv 文件

echo $stake--."</br>"; //find the larger sequence of this var and save to csv

提前感谢您的帮助

php csv sequence
1个回答
0
投票

当然!您可以修改代码以跟踪最长的序列,然后将该序列保存到 CSV 文件。这是代码的更新版本:

<?php

$stake = 500;
$times_to_run = 10000;
$i = 0;
$longest_sequence = 0;
$current_sequence = 0;

while ($i++ < $times_to_run) {
    $arr = array(1, 2, 3, 4, 5, 6, 7);
    $result = rand(0, 10);

    if (in_array($result, $arr)) {
        echo $stake++ . "</br>";
        echo "Win Result: " . $result . "</br></br>";
        // Reset the current sequence on a win
        $current_sequence = 0;
    } else {
        echo $stake-- . "</br>";
        // Increment the current sequence on a loss
        $current_sequence++;

        // Check if the current sequence is longer than the longest sequence
        if ($current_sequence > $longest_sequence) {
            $longest_sequence = $current_sequence;
        }
    }
}

// Save the longest sequence to a CSV file
$array = array_fill(0, $longest_sequence, $stake);
$fp = fopen('file.csv', 'w');
fputcsv($fp, $array);
fclose($fp);

?>

在这段代码中,$longest_sequence 用于存储循环过程中遇到的最长丢失序列的长度。当前序列长度 ($current_sequence) 在每次丢失时更新,如果它变得比最长序列长,则更新最长序列。

循环结束后,它会创建一个包含最长失败序列长度的数组,用当前赌注值填充该数组,并将其保存到 CSV 文件中。

© www.soinside.com 2019 - 2024. All rights reserved.