簡體   English   中英

PHP數組返回空值?

[英]Php array returns null?

我有php文件,可讀取文件並將其內容放入特定數組中。 這個php文件是一個單獨的文件。 因此,我將其包括在另一頁上。 當我要訪問另一個站點上的一個數組時,輸出為“ array(0){}”。 下面文件中的var_dump,但是返回一個包含所有6個項目的完整數組(按預期)。

這是我的php文件:

<?php

$englishTranslationsList = array();
$germanTranslationsList = array();
$timestampList = array();
$noteList = array();

function extractTranslationsFromFile($file){

    $handle = fopen($file, "r");
    if ($handle){

        while (($line = fgets($handle)) !== false) {

            $notelist[] = $line;

            $lineContent = substr($line, 3, strlen($line) - 1);

            switch(substr($line, 0, 3)):

            case "de:":  $germanTranslationsList[] = $lineContent;  break;
            case "en:":  $englishTranslationsList[] = $lineContent; break;
            case "ts:":  $timestampList[] = $lineContent; break;

            default: break;

            endswitch;

        }

        fclose($handle);

    }else{

        echo "<script>alert('ERROR')</script>";

    } 

    echo var_dump($germanTranslationsList);

}

?>

在包含它的網站上,我使用了

<p><?php echo var_dump($germanTranslationsList); ?></p>

上面顯示的只是一個空數組...我做錯了什么? 有辦法解決嗎?

您需要使用global關鍵字將全局變量引入函數的作用域:

<?php

$englishTranslationsList = array();
$germanTranslationsList = array();
$timestampList = array();
$noteList = array();

function extractTranslationsFromFile($file) {
    global $englishTranslationsList;
    global $germanTranslationsList;
    global $timestampList;
    global $noteList;

    // ...
}

警告

在A.php中包含B.php時,應注意在B.php中定義的文件路徑
因此,我想您已定義了一些相對文件路徑。

目錄結構

.
├── A.php
└── dir
    ├── a.txt
    └── B.php

A.php

require_once('dir/B.php');

B.php

$handle = fopen("a.txt", "r") or die("Unable to open file!");
echo fread($handle,filesize("a.txt"));
fclose($handle);

a.txt

Hello, world!

結果

在此處輸入圖片說明

運行B.php效果很好,打印“ Hello,world!”
但是,如果您運行A.php,它將顯示“無法打開文件!”

原因

運行B.php時, fopen()在B.php所在的目錄中搜索“ a.txt”。
但是,當運行A.php時, fopen()在A.php所在的目錄中搜索“ a.txt”。

忠告

使用絕對文件路徑而不是相對路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM