0

在 PHP 中的两个关联键之间获取数组切片的最简单方法是什么?

例如,对于数组

$arr = array('2012-02-01'=> 'bla blah',
'2012-02-02'=> 'bla blah',
'2013-02-03'=> 'bla blah',
'2012-02-04'=> 'bla blah',
'2012-02-05'=> 'bla blah',
'2010-03-06'=> 'bla blah',
'2012-04-07'=> 'bla blah',
'2012-01-08'=> 'bla blah',
'2012-02-09'=> 'bla blah',
'2012-10-10'=> 'bla blah',
'2012-12-03'=> 'bla blah');

如何获得 key: '2012-02-04' 和 key '2012-04-07' 之间的所有内容,这将是:

array('2012-02-04'=> 'bla blah',
'2012-02-05'=> 'bla blah',
'2010-03-06'=> 'bla blah',
'2012-04-07'=> 'bla blah')
4

1 回答 1

2

只要您确定两个键都在数组中:

$arr = array(
    '2012-02-01'=> 'bla blah',
    '2012-02-02'=> 'bla blah',
    '2013-02-03'=> 'bla blah',
    '2012-02-04'=> 'bla blah',
    '2012-02-05'=> 'bla blah',
    '2010-03-06'=> 'bla blah',
    '2012-04-07'=> 'bla blah',
    '2012-01-08'=> 'bla blah',
    '2012-02-09'=> 'bla blah',
    '2012-10-10'=> 'bla blah',
    '2012-12-03'=> 'bla blah'
);
$startKey = '2012-02-04';
$endKey = '2012-02-07';

$new = array_slice(
    $arr,
    array_search($startKey, array_keys($arr)),
    array_search($endKey, array_keys($arr)) - 
        array_search($startKey, array_keys($arr)) + 1
);
var_dump($new);

否则,在执行 array_slice() 之前,您需要对 array_search() 调用的返回值进行一些验证

于 2013-10-03T13:30:06.430 回答