写了2个函数,不明白我做错了什么

我越来越多地练习 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>';

}


免责声明:我真的很想让这两个功能正常工作,但我已经有了一个没有任何功能的工作替代方案(非常感谢!),这是我自己改进的学习机会,任何帮助将不胜感激!


森栏
浏览 163回答 1
1回答

蝴蝶不菲

你有几个问题。首先,$data = $fileData;应该是$data[] = $fileData;。添加[]意味着赋值在数组中创建一个新元素,而不是覆盖整个变量。当你在 的开头初始化变量时getFilesAndContent,它应该是$data = [];。第二,file_get_contents($fileInfo->getPathname())应该file_get_contents($path)。$fileInfo是 中的变量getFilesAndContent,不是getFileContents。第三,implode()应该explode()。implode连接数组以创建字符串,explode()将字符串拆分为数组。function getFilesAndContent($path){&nbsp; &nbsp; $data = [];&nbsp; &nbsp; $folderContents = new DirectoryIterator($path);&nbsp; &nbsp; foreach ($folderContents as $fileInfo) {&nbsp; &nbsp; &nbsp; &nbsp; if ($fileInfo->isDot()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $fileData = ['file_name' => $fileInfo->getBasename(),];&nbsp; &nbsp; &nbsp; &nbsp; if ($fileInfo->getExtension()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $fileData['contents'] = getFileContents($fileInfo->getPathname());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $data[] = $fileData;&nbsp; &nbsp; }&nbsp; &nbsp; return $data;}function getFileContents($path){&nbsp; &nbsp; $names = file_get_contents($path);&nbsp; &nbsp; $names = explode("\n", $names);&nbsp; &nbsp; sort($names);&nbsp; &nbsp; $contents = '';&nbsp; &nbsp; foreach ($names as $name) {&nbsp; &nbsp; &nbsp; &nbsp; $contents += $name . ' (' . strlen($name) . ')<br>';&nbsp; &nbsp; }&nbsp; &nbsp; return $contents;}foreach (getFilesAndContent('.') as $data) {&nbsp; &nbsp; echo $data['file_name'];&nbsp; &nbsp; echo '<br>';&nbsp; &nbsp; echo $data['contents'];&nbsp; &nbsp; echo '<hr>';}
打开App,查看更多内容
随时随地看视频慕课网APP