php获取两个数组键之间的子数组

时间:2014-03-19 08:25:22

标签: php arrays

在两个键之间获取数组子数组的最有效方法是什么。

例如,

$arr=array();
$arr['2014-03-01']='something';
$arr['2014-03-03']='something';
$arr['2014-02-04']='something';
$arr['2014-03-05']='something';
$arr['2014-03-07']='something';
$arr['2014-03-09']='something';
$arr['2014-01-04']='something';
$arr['2014-03-31']='something';

获取两个键之间的子阵列 即开始键:2014-02-04和结束键:2014-03-07应该只返回一个数组:

$arr['2014-02-04']='something';
$arr['2014-03-05']='something';
$arr['2014-03-07']='something';

是否有快速有效的方法在整个阵列中执行而不循环

更新:我在这里做了一个基准是结果:

$arr=array();
for ($i=1;$i<=1000000;$i++) {
    $arr["$i"]=$i;
}

$time_start=microtime_float();

$start = '20000';
$end   = '20010';

$offset = array_search($start, array_keys($arr));
$length = array_search($end, array_keys($arr)) - $offset + 1;
$output = array_slice($arr, $offset, $length);
print_r($output);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "TIME=$time\n";
echo "\n============\n";
$time_start=microtime_float();

$result = array();
$start = '20000';
$end   = '20010';

foreach ($arr as $key => $value) {
  if ($key >= $start && $key <= $end)
    $result[$key] = $value;
}
print_r($output);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "TIME=$time\n";

exit;

结果:

Array
(
    [0] => 20000
    [1] => 20001
    [2] => 20002
    [3] => 20003
    [4] => 20004
    [5] => 20005
    [6] => 20006
    [7] => 20007
    [8] => 20008
    [9] => 20009
    [10] => 20010
)
TIME=1.8481030464172

============
Array
(
    [0] => 20000
    [1] => 20001
    [2] => 20002
    [3] => 20003
    [4] => 20004
    [5] => 20005
    [6] => 20006
    [7] => 20007
    [8] => 20008
    [9] => 20009
    [10] => 20010
)
TIME=1.700336933136

因此,一个简单的循环似乎稍快一些。如果我在阵列中进一步开始,则优势会增加。你也可以使用break;一旦达到后一点。

2 个答案:

答案 0 :(得分:4)

最有效的方法是使用循环。

$result = array();
$start = '2014-02-04';
$end = '2014-03-07';

foreach ($arr as $key => $value) {
  // your date format is string comparable, otherwise use strtotime to convert to unix timestamp.
  if ($key >= $start && $key <= $end) {
    $result[$key] = $value;
  }
}

或者效率较低的方式是使用array_flip来交换密钥和值,然后使用array_filter来获取所需的密钥,然后使用array_intersect_key来获取结果。

答案 1 :(得分:2)

您可以尝试使用ksortarray_slicearray_search

$start = '2014-02-04';
$end   = '2014-03-07';

ksort($arr);
$offset = array_search($start, array_keys($arr));
$length = array_search($end, array_keys($arr)) - $offset + 1;
$output = array_slice($arr, $offset, $length);

var_dump($output);

输出:

array (size=5)
  '2014-02-04' => string 'something' (length=9)
  '2014-03-01' => string 'something' (length=9)
  '2014-03-03' => string 'something' (length=9)
  '2014-03-05' => string 'something' (length=9)
  '2014-03-07' => string 'something' (length=9)