首页 > 解决方案 > 合并来自多个 txt 文件的随机字符串并回显

问题描述

我想组合来自三个 txt 文件的随机字符串,但我不知道该怎么做。我的代码根本不起作用。

<?php

function jedan() {
    $f_contents = file("/ime/ime.txt"); 
    $line1 = $f_contents[rand(0, count($f_contents) - 1)];
} 

    function dva() {
    $f_contents = file("/prezime/prezime.txt"); 
    $line2 = $f_contents[rand(0, count($f_contents) - 1)];
    }

    function tri() {
    $f_contents = file("/email/email.txt"); 
    $line3 = $f_contents[rand(0, count($f_contents) - 1)];
    }


    $result = "{$line1}{$line2}{$line3}";
    echo $result

?>

标签: php

解决方案


你需要调用函数并返回一些东西。

function jedan() {
    $f_contents = file("/ime/ime.txt"); 
    return $f_contents[rand(0, count($f_contents) - 1)];
} 

function dva() {
    $f_contents = file("/prezime/prezime.txt"); 
    return $f_contents[rand(0, count($f_contents) - 1)];
}

function tri() {
    $f_contents = file("/email/email.txt"); 
    return $f_contents[rand(0, count($f_contents) - 1)];
}

$line1 = jedan();
$line2 = dva();
$line3 = tri();


$result = "{$line1}{$line2}{$line3}";
echo $result;

或者让它不那么“湿”:

function RandomLine($url) {
    $f_contents = file($url); 
    return $f_contents[rand(0, count($f_contents) - 1)];
} 

$line1 = RandomLine("/ime/ime.txt");
$line2 = RandomLine("/prezime/prezime.txt");
$line3 = RandomLine("/email/email.txt");


$result = "{$line1}{$line2}{$line3}";
echo $result;

推荐阅读