首頁  >  問答  >  主體

重寫後的標題為:將"Php合併兩個代碼(隨機 + 長度)"翻譯成中文

我需要你們的幫助來讓這個工作起來。 我需要將兩個php程式碼結合起來工作。 我是php的初學者,非常感謝你們給我的每一個建議。 提前謝謝!

描述:我想在我的index.php中顯示來自8個頁面的內容(一些文字),並以隨機順序顯示所取得的內容。 我不知道如何選擇從哪裡開始檢索頁面的文字數據,所以我選擇了字元選項(從1305個字元後開始,計數375個字元)。

程式碼1(選擇8個頁面並以隨機順序顯示它們)

<?php
$files = [
"folder/content1.php",
"folder/content2.php",
"folder/content3.php",
"folder/content4.php",
"folder/content5.php",
"folder/content6.php",
"folder/content7.php",
"folder/content8.php"
];
 shuffle($files);
foreach ($files as $key => $file) { require($file); }
?>

代碼2(從頁面中取得內容,從第1305個字元開始,只顯示375個字元)

<?php $section1 = file_get_contents("folder/content1.php", FALSE, NULL, 1305, 375); echo $section1; ?> </p>
<?php $section2 = file_get_contents("folder/content2.php", FALSE, NULL, 1305, 375); echo $section3; ?> </p>
<?php $section3 = file_get_contents("folder/content3.php", FALSE, NULL, 1305, 375); echo $section3; ?> </p>
<?php $section4 = file_get_contents("folder/content4.php", FALSE, NULL, 1305, 375); echo $section4; ?> </p>
<?php $section5 = file_get_contents("folder/content5.php", FALSE, NULL, 1305, 375); echo $section5; ?> </p>
<?php $section6 = file_get_contents("folder/content6.php", FALSE, NULL, 1305, 375); echo $section6; ?> </p>
<?php $section7 = file_get_contents("folder/content7.php", FALSE, NULL, 1305, 375); echo $section7; ?> </p>
<?php $section8 = file_get_contents("folder/content8.php", FALSE, NULL, 1305, 375); echo $section8; ?> </p>

我的合併程式碼不起作用

#
<?php
$files = [
"folder/content1.php",
"folder/content2.php",
"folder/content3.php",
"folder/content4.php",
"folder/content5.php",
"folder/content6.php",
"folder/content7.php",
"folder/content8.php"
 ];
 shuffle($files);
foreach ($files as $key => $file) file_get_contents("$files", FALSE, NULL, 1305, 375); { require($file); }
?>

P粉148782096P粉148782096373 天前584

全部回覆(1)我來回復

  • P粉349222772

    P粉3492227722023-09-16 10:24:06

    如果您對程式碼進行更好的格式化,可能會更容易理解。特別是最後兩行可能最好像這樣寫:

    foreach ($files as $key => $file) {
        file_get_contents("$files", FALSE, NULL, 1305, 375);
    }
    
    require($file);

    然後您可以看到問題所在:呼叫file_get_contents()的結果沒有被賦值給任何變量,所以它只是消失了;而您看到的是最後一個require() 的結果,它傳遞了上一個foreach循環中$file的最後一個值。

    實際上,file_get_contents()的呼叫看起來有問題- 第一個參數應該是一個字串,但您傳遞的是一個嵌入在字串中的陣列的名稱,這有點奇怪- 我沒有嘗試過,所以不確定會發生什麼。

    在我看來,無論循環中只有一個語句,都最好使用大括號 - 這樣做可以更容易避免錯誤。

    回覆
    0
  • 取消回覆