[英]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.