За последние 24 часа нас посетили 41820 программистов и 6832 робота. Сейчас ищут 1677 программистов ...

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

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

  1. lemonl

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

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

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

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

    MouseZver Суперстар

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

    Abyss Старожил

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

    PHP:
    1. <?php
    2. /**
    3. * Function for replacing elements in json-file
    4. * Writing rows as json strings into file
    5. * Watching for overflowing max rows count and popping top elements
    6. *
    7. * @param $filename string File name, possible absolute path, not tested, possibly works
    8. * @param $rows array|string Rows with already json_encode() lines, or one line
    9. * @param $rowsMax int Default rows limit for a file
    10. * @return void
    11. */
    12. function AddRowsToJsonFileWithRowsLimitByLine($filename, $rows, $rowsMax = 5){
    13.     if(!is_file($filename))
    14.         file_put_contents($filename, "[" . PHP_EOL . "]" . PHP_EOL);
    15.     // str -> arr
    16.     if(!is_array($rows))
    17.         $rows = [$rows];
    18.  
    19.     // in case count of incoming lines higher than our limit push diff from lines
    20.     if (($rowsCount = count($rows)) > $rowsMax && $rowsCount = $rowsMax)
    21.         $rows = array_slice($rows, -1, $rowsMax);
    22.  
    23.     // count total lines in parsing file
    24.     // wc -l easy hand
    25.     // if file not exists, or something, we take our limit as current lines count
    26.     $currentRowsCount = (
    27.         $currentLinesCount = (explode(" ", `wc -l $filename`)[0] ?? 0)
    28.     ) < 2 ?
    29.         0 :
    30.         $currentLinesCount - 2;
    31.  
    32.     // calculate shifting
    33.     $shiftLinesCount = $rowsCount + $currentRowsCount - $rowsMax;
    34.  
    35.     // source file
    36.     $sourceFile = fopen($filename, "r");
    37.     // temp file
    38.     $tempFile = fopen($filename . ".tmp", "w+");
    39.     // ignoring bracers cause they are not rows, and write them directly
    40.     fwrite($tempFile, "[" . PHP_EOL);
    41.  
    42.     while(!feof($sourceFile)){
    43.         $line = trim(fgets($sourceFile));
    44.         // skip lines for shifting
    45.         if(@$a++ > $shiftLinesCount && !in_array($line, ["[", "]"]) && $line)
    46.             fwrite($tempFile, $line . (str_ends_with($line, ",") ? "" : ",") . PHP_EOL);
    47.     }
    48.  
    49.     // write new rows and other
    50.     fwrite($tempFile, implode("," . PHP_EOL, $rows) . PHP_EOL . "]" . PHP_EOL);
    51.  
    52.     fclose($sourceFile);
    53.     fclose($tempFile);
    54.  
    55.     // backup dude, yeah
    56.     copy($filename, $filename . ".back");
    57.     // moving our temp file as new source
    58.     copy($filename . ".tmp", $filename);
    59.     // remove temporal
    60.     unlink($filename . ".tmp");
    61. }
    62.  
    63. AddRowsToJsonFileWithRowsLimitByLine("file.json", [
    64.     json_encode(["first_line_in_add_batch" => date("Y.m.d H:i:s")]),
    65.     json_encode(["second_line_in_add_batch" => date("Y.m.d H:i:s")]),
    66.     json_encode(["third_line_in_add_batch" => date("Y.m.d H:i:s")]),
    67. ]);