簡體   English   中英

寫了2個函數,不明白我做錯了什么

[英]Wrote 2 functions, don't understand what I did wrong

我越來越多地練習 PHP,並且每天都在嘗試執行函數以向它們學習。

昨天我寫了 2 個函數,但它們完全不起作用,我正在尋找原因的幫助!

我的代碼:

<?php

function getFilesAndContent($path)
{
    $data[] = $fileData;

    $folderContents = new DirectoryIterator($path);

    foreach ($folderContents as $fileInfo) {
        if ($fileInfo->isDot()) {
            continue;
        }

        $fileData = [
            'file_name' => $fileInfo->getBasename(),
        ];

        if ($fileInfo->getExtension()) {
            $fileData['contents'] = getFileContents($fileInfo->getPathname());
        }

        $data = $fileData;
    }

    return $data;
}

function getFileContents($path)
{
    $names = file_get_contents($fileInfo->getPathname());

    $names = implode("\n", $names);

    sort($names);

    $contents = '';

    foreach ($names as $name) {
        $contents += $name . ' (' . strlen($name) . ')<br>';
    }

    return $contents;
}

foreach (getFilesAndContent('.') as $data) {
    echo $data['file_name'];
    echo '<br>';
    echo $data['contents'];

    echo '<hr>';
}

免責聲明:我真的很想讓這兩個功能正常工作,但我已經有了一個沒有任何功能的工作替代方案(非常感謝!),這是我自己改進的學習機會,任何幫助將不勝感激!

你有幾個問題。

首先, $data = $fileData; 應該是$data[] = $fileData; . 添加[]意味着賦值在數組中創建一個新元素,而不是覆蓋整個變量。 當你在getFilesAndContent開頭初始化變量時,它應該是$data = []; .

其次, file_get_contents($fileInfo->getPathname())應該是file_get_contents($path) $fileInfogetFilesAndContent一個變量,而不是getFileContents

第三, implode()應該是explode() implode連接一個數組來創建一個字符串, explode()將一個字符串拆分成一個數組。

function getFilesAndContent($path)
{
    $data = [];
    $folderContents = new DirectoryIterator($path);
    foreach ($folderContents as $fileInfo) {
        if ($fileInfo->isDot()) {
            continue;
        }
        $fileData = ['file_name' => $fileInfo->getBasename(),];
        if ($fileInfo->getExtension()) {
            $fileData['contents'] = getFileContents($fileInfo->getPathname());
        }
        $data[] = $fileData;
    }
    return $data;
}

function getFileContents($path)
{
    $names = file_get_contents($path);
    $names = explode("\n", $names);
    sort($names);
    $contents = '';
    foreach ($names as $name) {
        $contents += $name . ' (' . strlen($name) . ')<br>';
    }
    return $contents;
}

foreach (getFilesAndContent('.') as $data) {
    echo $data['file_name'];
    echo '<br>';
    echo $data['contents'];
    echo '<hr>';
}

暫無
暫無

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

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