在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');
怎样才能在密钥之间得到一切:'2012-02-04'和关键'2012-04-07' 这将是:
array('2012-02-04'=> 'bla blah',
'2012-02-05'=> 'bla blah',
'2010-03-06'=> 'bla blah',
'2012-04-07'=> 'bla blah')
答案 0 :(得分:1)
只要你确定两个键都在数组中:
$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()调用的返回进行一些验证。