PHP 数组仅获取那些 elements/values 其键匹配特定模式的数组
PHP Array only get those elements/values whose keys match a particular pattern
我有一个多维嵌套数组,如下所示:
Array
(
[_edit_lock] => Array
(
[0] => 1504299434:6
)
[_edit_last] => Array
(
[0] => 6
)
[additional_photos_0_gallery_image_1] => Array
(
[0] => 77556
)
[additional_photos_0_gallery_image_2] => Array
(
[0] => 77567
)
[additional_photos_0_gallery_image_3] => Array
(
[0] => 73768
)
....
)
现在我只需要获取给定数组的那些元素(在不更改当前数组的单独数组中),其键与特定模式匹配,如下所示:
additional_photos_[any_number]_gallery_image_[any_number]
如何才能使用数组函数之一并避免 foreach
循环?
只需使用 array_filter 和 preg_match。
return array_filter($data, function($key) {
return preg_match('~^additional_photos_[0-9]+_gallery_image_[0-9]+$~', $key);
}, ARRAY_FILTER_USE_KEY);
我有一个多维嵌套数组,如下所示:
Array
(
[_edit_lock] => Array
(
[0] => 1504299434:6
)
[_edit_last] => Array
(
[0] => 6
)
[additional_photos_0_gallery_image_1] => Array
(
[0] => 77556
)
[additional_photos_0_gallery_image_2] => Array
(
[0] => 77567
)
[additional_photos_0_gallery_image_3] => Array
(
[0] => 73768
)
....
)
现在我只需要获取给定数组的那些元素(在不更改当前数组的单独数组中),其键与特定模式匹配,如下所示:
additional_photos_[any_number]_gallery_image_[any_number]
如何才能使用数组函数之一并避免 foreach
循环?
只需使用 array_filter 和 preg_match。
return array_filter($data, function($key) {
return preg_match('~^additional_photos_[0-9]+_gallery_image_[0-9]+$~', $key);
}, ARRAY_FILTER_USE_KEY);