-4

我有这样的数组:

array(8) {
  ["2013-01-02"]  =>  27.62,
  ["2013-01-03"]  =>  27.25,
  ["2013-01-04"]  =>  26.74,
  ["2013-01-07"]  =>  26.69,
  ["2013-01-08"]  =>  26.55,
  ["2013-01-09"]  =>  26.70,
  ["2013-01-10"]  =>  26.46,
  ["2013-01-11"]  =>  26.83
}

我想找到 n 的所有变化。

例如 n=3 的结果:

array(6) {  
  array(3) {
    ["2013-01-02"]  =>  27.62,
    ["2013-01-03"]  =>  27.25,
    ["2013-01-04"]  =>  26.74    
  }
  array(3) {
    ["2013-01-03"]  =>  27.25,
    ["2013-01-04"]  =>  26.74,
    ["2013-01-07"]  =>  26.69
  }
  array(3) {
    ["2013-01-04"]  =>  26.74,
    ["2013-01-07"]  =>  26.69,
    ["2013-01-08"]  =>  26.55
  }
  array(3) {
    ["2013-01-07"]  =>  26.69,
    ["2013-01-08"]  =>  26.55,
    ["2013-01-09"]  =>  26.70
  }
  array(3) {
    ["2013-01-08"]  =>  26.55,
    ["2013-01-09"]  =>  26.70,
    ["2013-01-10"]  =>  26.46
  }
  array(3) {
    ["2013-01-09"]  =>  26.70,
    ["2013-01-10"]  =>  26.46,
    ["2013-01-11"]  =>  26.83
  }
}

如何在 PHP 中轻松做到这一点?

就是这样,但没有这个我不能提交:在计算机科学中,关联数组、映射或字典是由(键、值)对的集合组成的抽象数据类型,这样每个可能的键最多出现一次在集合中。

4

1 回答 1

0

使用您的旧数组并通过对 的各种调用构建一个新数组array_slice(),如下所示:

$new_array = array();
$n = 3;
$size = count( $old_array) - $n; // Assumes you have at least $n elements, should check for this
for( $i = 0; $i <= $size; $i++) {
    $new_array[] = array_slice( $old_array, $i, $n);
}

一个print_r( $new_array);产量:

Array
(
    [0] => Array
        (
            [2013-01-02] => 27.62
            [2013-01-03] => 27.25
            [2013-01-04] => 26.74
        )

    [1] => Array
        (
            [2013-01-03] => 27.25
            [2013-01-04] => 26.74
            [2013-01-07] => 26.69
        )

    [2] => Array
        (
            [2013-01-04] => 26.74
            [2013-01-07] => 26.69
            [2013-01-08] => 26.55
        )

    [3] => Array
        (
            [2013-01-07] => 26.69
            [2013-01-08] => 26.55
            [2013-01-09] => 26.7
        )

    [4] => Array
        (
            [2013-01-08] => 26.55
            [2013-01-09] => 26.7
            [2013-01-10] => 26.46
        )

    [5] => Array
        (
            [2013-01-09] => 26.7
            [2013-01-10] => 26.46
            [2013-01-11] => 26.83
        )

)
于 2013-02-07T19:33:42.313 回答