首页 > 解决方案 > 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']

标签: phparraysstringsorting

解决方案


定义您正在寻找的不同类型的扩展。

$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每个扩展类型获取数组中的第一个元素。


推荐阅读