我正在尝试重命名数组中的上传文件。
每个元素(在本例中为2个)包含文件路径/名称。 (filename_a和filename_b)
当我运行脚本并回显结果时,我得到以下内容:
filename: filename_a
basename: filename_a.jpg
extension: jpg
newfilename: 17_0.jpg
filename: filename_a
basename: filename_a.jpg
extension: jpg
newfilename: 17_1.jpg
filename: filename_a
basename: filename_a.jpg
extension: jpg
newfilename: 17_2.jpg
filename: filename_a
basename: filename_a.jpg
extension: jpg
newfilename: 17_3.jpg
我期待:
filename: filename_a
basename: filename_a.jpg
extension: jpg
newfilename: 17_0.jpg
filename: **filename_b**
basename: **filename_b.jpg**
extension: jpg
newfilename: 17_1.jpg
第二个元素(文件名)未更改。仍然显示第一个文件名和echos 4而不是数组中的两个元素。不遍历数组。
代码:
foreach( $_POST['ax-uploaded-files'] as $filepath)
{
$path_parts = pathinfo($filepath);
}
for ($i = 0; $i < count($path_parts); ++$i) {
$basename = $path_parts['basename'];
$filename = $path_parts['filename'];
$extension = $path_parts['extension'];
$newfilename = $submission_id . '_' . $i . '.' . $extension;
echo '<br>filename: ' . $filename;
echo '<br>basename: ' . $basename;
echo '<br>extension: ' . $extension;
echo '<br>newfilename: ' . $newfilename . '<br>';
rename("photos/".$submission_id."/primary/".$filename.".".$extension, "photos/".$submission_id."/primary/" .$newfilename);
}
我没有包含重命名代码,因为它本身就可以工作。有什么建议?
答案 0 :(得分:1)
在顶部foreach
循环中,您在不使用变量的情况下多次写入$path_parts
。这两个循环应合并为一个。
试试这个:
$a = array('filepath/fa.jpg', 'filepath/fb.jpg');
$submission_id = 17;
$i = 0;
foreach( $a as $filepath)
{
$path_parts = pathinfo($filepath);
$basename = $path_parts['basename'];
$filename = $path_parts['filename'];
$extension = $path_parts['extension'];
$newfilename = $submission_id . '_' . $i . '.' . $extension;
echo '<br>filename: ' . $filename;
echo '<br>basename: ' . $basename;
echo '<br>extension: ' . $extension;
echo '<br>newfilename: ' . $newfilename . '<br>';
$i++;
}
输出:
filename: fa
basename: fa.jpg
extension: jpg
newfilename: 17_0.jpg
filename: fb
basename: fb.jpg
extension: jpg
newfilename: 17_1.jpg