简体   繁体   English

如何从PHP中的复杂多维数组获取值并将其转换为字符串

[英]How to get values from complex multidimensional arrays in PHP and turn them into strings

I've very complex array that I would like to get values for HTML creation. 我有一个非常复杂的数组,我想获取HTML创建的值。

I have in my array a list of jpg files in directories, but I want all the files from 'materialy-do-plis' directory that have subdirectories with files and sometimes even more subsubdirectories with more files. 我在数组中有一个目录中的jpg文件列表,但我希望“ materialy-do-plis”目录中的所有文件都包含带有文件的子目录,有时甚至是带有更多文件的子目录。

I would like to get in foreach array a nicely generated urls with directory names and files at the end. 我想在foreach数组中获得一个生成良好的url,并在其末尾添加目录名称和文件。

And this is my code to get it, if that helps: 这是我得到的代码,如果有帮助的话:

function pathToArray($path , $separator = '/') {
    if (($pos = strpos($path, $separator)) === false) {
        return array($path);
    }
    return array(substr($path, 0, $pos) => pathToArray(substr($path, $pos + 1)));
}


$dir = APPPATH.'../media/multimedia/obrazy/materialy-do-plis/';
$results = array();
if (is_dir($dir)) {
    $iterator = new RecursiveDirectoryIterator($dir);
    foreach ( new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file ) {
        if ($file->isFile()) {
            $thispath = str_replace('\\', '/', $file);
            $thisfile = utf8_encode($file->getFilename());
            $results = array_merge_recursive($results, pathToArray($thispath));
        }
    }
}
echo "<pre>";
print_r($results);

array_walk($products, function ($value, $key) use ($stores, &$array) {
    $array[$value['store']][] = $value['product'];
});

print_r($array);

Basically I think, you need a recursing function. 基本上,我认为您需要一个递归函数。 This function could write to a result array, that might either be a class variable or passed in by reference. 该函数可以写入结果数组,该结果数组可以是类变量,也可以通过引用传递。

Basically like this (untested, but to get the idea): 基本上是这样的(未经测试,但可以理解):

class Foo {
    private $results = array();

    function recurse($inputArray, $path) {
        foreach($inputArray as $i => $item) {
            if(is_dir($path."/".$i)) {
                $this->recurse($item, $path."/".$i);
            }elseif(is_file($path."/".$item)){
                $this->results[] = $path."/".$item;
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM