2017-10-17 34 views
0

对于PHP来说是相当新的,所以如果这是一个微不足道的问题,请原谅我。得到阵列中正则表达式匹配的次数

我正在创建一个基于包含具有几种不同命名约定的图像的目录的数组。这里的阵列结构的一些示例代码:

<?php 
    $path = '../regions'; //path contains child directories north/, west/, south/, etc. 
     //each of these child directories contains images listed in Array below 

    $regions = array_flip(array_diff(scandir($path), array('.', '..'))); 
     // $regions = Array([north] => [2], [west] => [3], ..., [south] => [6]) 

    foreach ($regions as $key => $value) { 
     $images = array_diff(scandir($path.'/'.$key.'/'.$regionkey), array('.', '..')); 
     $regions[$key] = $images; 
      //$regions is now the Array shown in code section below 
    } 

?> 

由代码产生的阵列上方看起来大致是这样的:

[north] => Array(
    [2] => windprod_f1.png 
    [3] => windprod_f2.png 
    ... 
    [20] => windprod_f18.png 
    [21] => temp_sim_f1.png 
    [22] => temp_sim_f2.png 
    ... 
    [36] => temp_sim_f16.png 
    [37] => pres_surf_f1.png 
    [38] => pres_surf_f2.png 
    [45] => pres_surf_f9.png 
    ... 
) 
[south] => Array (
    [2] => windprod_f1.png 
    [3] => windprod_f2.png 
    ... 
    [20] => windprod_f18.png 
    [21] => temp_sim_f1.png 
    [22] => temp_sim_f2.png 
    ... 
    [32] => temp_sim_f12.png 
    [33] => pres_surf_f1.png 
    [34] => pres_surf_f2.png 
    ... 
    [58] => pres_surf_f24.png 
    .... 
) 
... 

有5个唯一的文件命名约定(windprod,temp_sim,pres_surf等),每个图像都有一些不同数量的图像(_f1,_f2,...,f_18等)。像我这样完成数组构建之后,我需要为每个特定文件命名约定获取图像的数量。理想情况下,我希望$ key是产品名称(每个文件名中的_f(\d{1,2}).png之前的子字符串),$ value是包含该数组中特定子字符串的文件数。

即,我最后的数组必须是这样的:

[north] => Array (
    [windprod] => 18 //$key = regex match, $values = number of matches in Array 
    [temp_sim] => 16 
    [pres_surf] => 9 
    ... 
    ) 
[south] => Array (
    [windprod] => 18 
    [temp_sim] => 12 
    [pres_surf] => 24 
    ... 
    ) 
... 

任何人有什么想法吗?

感谢所有提前。

回答

0

简单的迭代应该可以正常工作,我认为,这样的事情

foreach ($regions as $region => $images) { 
    $result = []; 
    foreach ($images as $image) { 
     $type = preg_replace('/_f\d+\.png$/', '', $image); 
     if (!array_key_exists($type, $result)) { 
      $result[$type] = 0; 
     } 
     $result[$type]++; 
    } 
    $regions[$region] = $result; 
}