2017-10-17 9 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など)が関連付けられています。私が行ったように配列を作成したら、それぞれの特定のファイル命名規則のためにイメージの数を取得する必要があります。理想的には、$キーを製品名(それぞれのファイル名に_f(\d{1,2}).pngの前の部分文字列)とし、$値を配列内のその特定の部分文字列を含むファイルの数にします。

すなわち、私の最後の配列はこのように見ています

[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; 
} 
のようなものが正常に動作する必要があります
関連する問題