2017-10-17 48 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; 
}