1

我正在尝试获取任何具有“release_”键的数据......我想我应该使用 array_filter,但我很难为参数 2 编写正确的函数。

这是我的数组:

Array
    (
    [release_date] => Array
        (
            [type] => date
            [value] => 1999-03-31
        )

    [duration] => Array
        (
            [type] => time
            [value] => 136
        )
    [directors] => Array
        (
            [type] => page
            [value] => 13,14
        )
    [writers] => Array
        (
            [type] => page
            [value] => 13,14
        )
    [release_us] => Array
        (
            [type] => date
            [value] => 1999-03-30
        )
    [release_ge] => Array
        (
            [type] => date
            [value] => 1999-06-16
        )
    )

我希望我的返回数组只有 release_ 存在的数组..所以它看起来像:

Array
    (
    [release_date] => Array
        (
            [type] => date
            [value] => 1999-03-31
        )

    [release_us] => Array
        (
            [type] => date
            [value] => 1999-03-30
        )
    [release_ge] => Array
        (
            [type] => date
            [value] => 1999-06-16
        )
    )
4

2 回答 2

2
function preg_grep_keys( $pattern, $input, $flags = 0 )
{
    $keys = preg_grep( $pattern, array_keys( $input ), $flags );
    $vals = array();
    foreach ( $keys as $key )
    {
        $vals[$key] = $input[$key];
    }
    return $vals;
}

用法:

preg_grep_keys("/release_/", $yourArray);

于 2013-04-14T17:17:54.487 回答
1

只需创建一个foreach循环遍历您的原始数组:

$nArr = array();
foreach($arr as $key => $value) {
    if(strpos($key, 'release_') !== false) {
        $nArr[$key] = $value;
    }
}

编辑

或以函数形式:

function checkKeys($arr, $keyCheck) {
    $nArr = array();
    foreach($arr as $key => $value) {
        if(strpos($key, $keyCheck) !== false) {
            $nArr[$key] = $value;
        }
    }
    return $nArr;
}

然后使用$release = checkKeys($myArray, 'release_');

于 2013-04-14T17:21:21.173 回答