如何按键切片数组,而不是偏移


How to slice an array by key, not offset?

PHP函数array_slice()按偏移量返回元素序列,如下所示:

// sample data
$a = array('a','b','c',100=>'aa',101=>'bb',102=>'cc'); 
// outputs empty array because offset 100 not defined
print_r(array_slice($a,100));

当前函数参数:

array_slice ( $array, $offset, $length, $preserve_keys) 

我需要这样的东西:

array_slice ( $array, **$key**, $length, $preserve_keys) 

根据上面的print_r输出:

array (
   100 => aa,
   101 => bb,
   102 => cc
)

要查找键的偏移量,使用array_search()搜索键,可以使用array_keys()检索键。当指定的键(100)不存在于数组($a)中时,array_search()将返回FALSE

$key = array_search(100, array_keys($a), true);
if ($key !== false) {
    $slice = array_slice($a, $key, null, true);
    var_export($slice);
}

打印:

array (
  100 => 'aa',
  101 => 'bb',
  102 => 'cc',
)

返回$array中键存在于数组$keys中的部分:

array_intersect_key($array,array_flip($keys));

备选方案

如果您希望通过使用键来获取项对数组进行切片,可以使用以下自定义函数:

function array_slice_keys($array, $keys = null) {
    if ( empty($keys) ) {
        $keys = array_keys($array);
    }
    if ( !is_array($keys) ) {
        $keys = array($keys);
    }
    if ( !is_array($array) ) {
        return array();
    } else {
        return array_intersect_key($array, array_fill_keys($keys, '1'));
    }
}

用法:

$ar = [
    'key1' => 'a',
    'key2' => 'b',
    'key3' => 'c',
    'key4' => 'd',
    'key5' => 'e',
    'key6' => 'f',
];
// Get the values from the array with these keys:
$items = array_slice_keys( $ar, array('key2', 'key3', 'key5') );

结果:

Array
(
    [key2] => b
    [key3] => c
    [key5] => e
)