【发布时间】:2019-09-24 16:01:58
【问题描述】:
我正在尝试从文件夹内的文件夹中获取文件名(../merchant_assets/ 文件夹内有一个名为 1 的文件夹,我正在尝试获取该文件夹内的所有名称文件)
下面的代码工作正常,但是当我将包含结果$temp 的数组分配给stdClass() 变量$container 时,当我尝试在函数print_r($container->screenshots) 之外打印出数组时,它变为空但是如果我在函数内部打印出来它就可以了
<?php
include 'config.php';
$url = "http://" . $_SERVER['HTTP_HOST'] . '/merchant_assets/';
$target = '../merchant_assets';
$merchant_id = 1;
$container = new stdClass();
$folder = '';
// Call the function
dir_contents_recursive($target);
// Get all screenshots images from merchant_assets folder based on merchant_id
function dir_contents_recursive($dir) {
// open handler for the directory
global $container;
$iter = new DirectoryIterator($dir);
$temp = Array();
foreach( $iter as $item ) {
// make sure you don't try to access the current dir or the parent
if ($item != '.' && $item != '..') {
if( $item->isDir() ) {
// call the function on the folder
global $merchant_id, $folder;
if($merchant_id == $item->getFilename()) {
$folder = $item->getFilename();
dir_contents_recursive("$dir/$item");
}else
continue;
} else {
// print files
global $url, $folder;
$current_index = count($temp);
$temp[$current_index] = $url . $folder . '/' . $item->getFilename();
}
}
}
$container->screenshots = $temp;
print_r($container->screenshots); // It shows the results
}
// Handle response
$response = $container;
print_r($container->screenshots); // No results???
$response_json = json_encode($response);
echo $response_json;
?>
我希望输出是
[我故意将每个索引的值改为item]
Array (
[0] => item
[1] => item
[2] => item
[3] => item
【问题讨论】:
-
不能在函数外调用$container
-
@fmsthird 实际上他可以作为
$container的原始定义在函数之外。但我不建议使用全局变量。为什么不从函数中返回对象?