php - php使用包含名称的js文件重命名文件
问题描述
是否可以使用 php 重命名目录中的文件以匹配创建的 js 文件的输出。我从我正在使用的 API 下载了数千张图像,但将我的应用程序切换到了新的 API,并且必须将旧的 imageID 与新的 imageID 匹配。我宁愿批量重命名文件,而不是加载 js 文件来获取新的 id 名称。我在 php 方面的经验很少,所有的教程都是简单的文件重命名,没有比这更复杂的了。
img.js
var img_ar = {
"pid_12685":"2578377",
"pid_12757":"2980444",
"pid_12916":"3056906"
}
当前图像文件名 /images
2578377.png
2980444.png
3056906.png
运行 php 脚本后所需的文件名
pid_12685.png (old file name 2578377.png)
pid_12757.png (old file name 2980444.png)
pid_12916.png (old file name 3056906.png)
解决方案
您可以制作一个 php 脚本(在您的网络服务器中不需要),然后通过php your_script.php
在该脚本中,您可以使用scandir获取图像目录中所有图像的数组
然后您必须遍历该数组并使用重命名函数重命名图像
因为我没有看到旧名称编号和新名称编号之间的关系,所以您可以创建一个数组
$names = [
'2578377.png' => 'pid_12685.png'
'2980444.png' => 'pid_12757.png'
'3056906.png' => 'pid_12916.png'
];
然后,在你的循环中rename($imageName, $names[$imageName]);
你可以使用这个脚本:
将脚本放在您的图像目录中,或更改 $path 变量,以便脚本将使用正确的目录
更改 $names 以包含所有图像
<?php $path = '.'; $files = array_diff(scandir($path), ['.', '..']); $names = [ '2578377.png' => 'pid_12685.png', '2980444.png' => 'pid_12757.png', '3056906.png' => 'pid_12916.png' ]; foreach($files as $file){ if(is_file($file) && isset($names[$file])){ rename($file, $names[$file]); } }
通过调用脚本
php script_name.php
推荐阅读
- java - 通知访问允许但切换未更改
- c++ - 是否可以在 C++ 中创建自己的宏以供 QMake 稍后解决?
- ios - 为什么 url.bookmarkData 返回 nil?
- javascript - 具有二维数组的角度复选框
- visual-studio - 如何在颤动/飞镖扩展中禁用蓝色警告下划线标志?
- c - 如果子线程被套接字读取阻塞,如何通过管道通知主线程?
- python - 为什么 for 循环中定义的子图表现不一致?('numpy.ndarray' 对象没有属性'plot')
- php - Laravel SQLSTATE[HY000] [1049] 未知数据库 + PHP 工匠迁移
- javascript - 向下滑动汉堡菜单
- angular - 将 http 响应映射到类型参数中的对象数组