php - PHP array of string pick 2 elements only
问题描述
I have an array of string. Each string is a filename. Each file name is either an image ('.jpg', '.jpeg', '.png') or a video/audio ('.mp4', '.mov', '.flv', '.mp3').
Example :
$files [] = ['file1.jpg', 'file2.mp4', 'file3.mov', 'file4.flv', 'file5.png'];
How can I create a new array from the $files
array with two filenames only of different type e.g. 1 video and 1 image like :
['file1.jpg', 'file3.mov']
or ['file1.jpg', 'file2.mp4']
解决方案
定义您正在寻找的不同类型的扩展。
$extension_types = [
'image' => ['jpg', 'jpeg', 'png'],
'video' => ['mp4', 'mov', 'flv', 'mp3']
];
然后,对于这些类型中的每一种,迭代 files 数组,直到找到具有其中一个扩展名的文件。将其添加到您的结果中,然后继续下一个类型。
foreach ($extension_types as $type => $extensions) {
foreach ($files as $file) {
if (in_array(pathinfo($file, PATHINFO_EXTENSION), $extensions)) {
$result[] = $file;
break;
}
}
}
这将为$files
每个扩展类型获取数组中的第一个元素。
推荐阅读
- vue.js - 异步任务在 vuejs 视图中不是响应式的
- python - 上传从 cv2.imdecode() 返回的图像时面临问题
- ruby - 如何在 ruby 中一次访问多行
- bash - 将字符从 Windows 转义到 WSL
- c# - Xamarin Android 的列表视图中未加载嵌入式资源
- android - 如何在 Android 中测量画布上的手绘图像?
- javascript - 有什么方法可以在双精度中获得超过 13 个小数点?C# 还是 JS?
- javascript - noUiSlider 多范围访问第一个句柄
- database - 使用常规数据库作为数据仓库
- ruby - 如何从终端 unsig ruby 中的文本背景中删除颜色?