[英]Get count of regex matches in array
對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
...
)
...
有人在這里有什么想法嗎?
在此先感謝所有。
我認為,簡單的迭代應該可以正常工作
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.