I have array like this:
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
}
And I want to find all variations by n.
For example result for 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
}
}
How can I easily do this in PHP?
That's all, but I can't submit it without this: In computer science, an associative array, map, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.
Take your old array and build a new one with various calls to array_slice()
, like this:
$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);
}
A print_r( $new_array);
yields:
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
)
)