drcx71276 2017-09-02 13:05
浏览 33
已采纳

PHP数组仅获取其键与特定模式匹配的元素/值

I have a multi-dimensional & nested array like below:

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
        )
    ....
)

Now I need to get only those elements of the given array(in a separate array without changing current array), whose keys match a particular pattern like below:

additional_photos_[any_number]_gallery_image_[any_number]

How can I get using one of the array functions and avoiding foreach loops ?

  • 写回答

1条回答 默认 最新

  • dourou9477 2017-09-02 13:09
    关注

    Just use array_filter and preg_match.

    return array_filter($data, function($key) {
        return preg_match('~^additional_photos_[0-9]+_gallery_image_[0-9]+$~', $key);
    }, ARRAY_FILTER_USE_KEY);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?