PHP 将配对值添加到数组中,然后排序并打印
假设我有一个文件的名称及其在两个变量中的完整路径,如何将它们添加到数组中,按文件名对数组进行排序(保持两个值配对,然后循环遍历数组并打印它?这是使用我不会列出整个代码,因为它非常复杂,所以这是我想要做的事情的简化版本:
<?php
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($pathToIterate));
foreach($files as $file){
$path=str_replace($_SERVER["DOCUMENT_ROOT"],'',$file->getPathname());
$file_name = basename($path,'.'.$info['extension']);
// Need code to add $file_name and $path to array //
};
}
// Need code to sort array by $file_name //
// Need code to loop through array and print <a href="$path">$file_name</a> //
}
?>
Say I have the name of a file and it's full path in two variables, how can I add them to an array, sort the array by the filename (keeping the two values paired, then loop through the array and print it? This is using a directory iterator. I won't list the whole code as it's quite convuluted, so heres a simplified version of what I'm trying to do:
<?php
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($pathToIterate));
foreach($files as $file){
$path=str_replace($_SERVER["DOCUMENT_ROOT"],'',$file->getPathname());
$file_name = basename($path,'.'.$info['extension']);
// Need code to add $file_name and $path to array //
};
}
// Need code to sort array by $file_name //
// Need code to loop through array and print <a href="$path">$file_name</a> //
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:更新感谢难以捉摸的建议
EDIT: Updated thanks to elusive's suggestion
我会将每一对维护在一个简单的类中。然后我会使用 usort(),它允许您对数组进行排序使用用户定义的比较函数。
我已经有一段时间没有编写任何 PHP 了,所以我可能会因为以下(未经测试的)示例代码而让自己感到尴尬,但您应该明白这个想法:
I would maintain each pair in a simple class. Then I would use usort(), which allows you to sort an array using a user-defined comparison function.
It's been a while since I've written any PHP, so I might be embarrassing myself with the following (untested) example code, but you should get the idea: