Пример очереди FIFO

Тема в разделе "PHP для новичков", создана пользователем lemonl, 7 сен 2022.

  1. lemonl

    lemonl Активный пользователь

    С нами с:
    10 июн 2009
    Сообщения:
    164
    Симпатии:
    0
    Здравствуйте господа,

    Подскажите(помогите) пожалуйста создать небольшой пример такой очереди на PHP

    Есть JSON файл типа в нем 6 записей:
    Код:
    [
    
    {"t":1390017600,"hot":1,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":2,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":3,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":4,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":5,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":6,"koto":0.028,"rop":0.028}
    ]
    При добавлении 7 записи нужно удалить первую запись
    Код:
    {"t":1390017600,"hot":1,"koto":0.028,"rop":0.028}
    Таким образом JSON файлик должен иметь вид
    Код:
    [
    {"t":1390017600,"hot":2,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":3,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":4,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":5,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":6,"koto":0.028,"rop":0.028},
    {"t":1390017600,"hot":7,"koto":0.028,"rop":0.028}
    ]
    Благодарсвую за помощь господа !
     
  2. MouseZver

    MouseZver Суперстар

    С нами с:
    1 апр 2013
    Сообщения:
    7.844
    Симпатии:
    1.338
    Адрес:
    Лень
    array_shift
    array_push
    json_encode
    json_decode
    google.com
     
  3. Abyss

    Abyss Старожил

    С нами с:
    12 дек 2015
    Сообщения:
    1.294
    Симпатии:
    216
    Адрес:
    Default city
    Никакой фантазии.

    PHP:
    <?php
    /**
    * Function for replacing elements in json-file
    * Writing rows as json strings into file
    * Watching for overflowing max rows count and popping top elements
    *
    * @param $filename string File name, possible absolute path, not tested, possibly works
    * @param $rows array|string Rows with already json_encode() lines, or one line
    * @param $rowsMax int Default rows limit for a file
    * @return void
    */
    function AddRowsToJsonFileWithRowsLimitByLine($filename, $rows, $rowsMax = 5){
        if(!
    is_file($filename))
            
    file_put_contents($filename, "[" . PHP_EOL . "]" . PHP_EOL);
        
    // str -> arr
        
    if(!is_array($rows))
            
    $rows = [$rows];

        
    // in case count of incoming lines higher than our limit push diff from lines
        
    if (($rowsCount = count($rows)) > $rowsMax && $rowsCount = $rowsMax)
            
    $rows = array_slice($rows, -1, $rowsMax);

        
    // count total lines in parsing file
        // wc -l easy hand
        // if file not exists, or something, we take our limit as current lines count
        
    $currentRowsCount = (
            
    $currentLinesCount = (explode(" ", `wc -l $filename`)[0] ?? 0)
        ) < 
    2 ?
            
    0 :
            
    $currentLinesCount - 2;

        
    // calculate shifting
        
    $shiftLinesCount = $rowsCount + $currentRowsCount - $rowsMax;

        
    // source file
        
    $sourceFile = fopen($filename, "r");
        
    // temp file
        
    $tempFile = fopen($filename . ".tmp", "w+");
        
    // ignoring bracers cause they are not rows, and write them directly
        
    fwrite($tempFile, "[" . PHP_EOL);

        while(!
    feof($sourceFile)){
            
    $line = trim(fgets($sourceFile));
            
    // skip lines for shifting
            
    if(@$a++ > $shiftLinesCount && !in_array($line, ["[", "]"]) && $line)
                
    fwrite($tempFile, $line . (str_ends_with($line, ",") ? "" : ",") . PHP_EOL);
        }

        
    // write new rows and other
        
    fwrite($tempFile, implode("," . PHP_EOL, $rows) . PHP_EOL . "]" . PHP_EOL);

        
    fclose($sourceFile);
        
    fclose($tempFile);

        
    // backup dude, yeah
        
    copy($filename, $filename . ".back");
        
    // moving our temp file as new source
        
    copy($filename . ".tmp", $filename);
        
    // remove temporal
        
    unlink($filename . ".tmp");
    }

    AddRowsToJsonFileWithRowsLimitByLine("file.json", [
        
    json_encode(["first_line_in_add_batch" => date("Y.m.d H:i:s")]),
        
    json_encode(["second_line_in_add_batch" => date("Y.m.d H:i:s")]),
        
    json_encode(["third_line_in_add_batch" => date("Y.m.d H:i:s")]),
    ]);