I’m not terribly well versed with array manipulation in PHP, so I have a simple porting question. In C++ I have a map std::map<int, int>, for which the implicit ordering on the key is a crucial part of the structure. What I want to do is to sum up all the values for an initial range of keys, which I do like this:
// accumulate helper, since "value_type" is "pair<int, int>"
int pair_adder(int n, const std::map<int, int>::value_type & p) { return n + p.second; }
// To add up values for keys up to N:
int total_value_up_to_time_N(int N)
{
return std::accumulate(mymap.begin(), mymap.upper_bound(N), 0, pair_adder);
}
What would be an idiomatic way to write this data structure and accumulator in PHP?
To explain the context: The data structure is a simple time series, and I want to know how much I have accumulated at time N. The C++ map is always sorted by key, so I can add elements mymap[time] = value; in any order, and the map always contains the elements in time order.
To explain the accumulation: The accumulate function sums up all the map’s values whose keys are no greater than N. For example, take this map:
mymap = { { 1, 20}, {2, 30}, {3, -10}, {4, 15} };
Then for N = 2 I accumulate 50, for N = 3 I accumulate 40, and for N = 12 I accumulate 55.
Update: I just realized that actually there’s no reason why each timestamp should occur only once, so the data structure should really be a std::multimap<int, int>. The same accumulation function works verbatim, but if the PHP solution requires the time to be an array key, than that would no longer work. But this is not strictly important; I believe a solution in which each time is required to be unique will suffice.
Unfortunately, the PHP array map/reduce functions only map over values, not keys. If your map is using PHP
key => valuearrays, you’ll need some tricks to filter out the values whose keys have a certain value. The easiest is a straight forward loop:From here you can of course get creative though:
Or:
If you’re using a more C++ like map, which in PHP would be an array of arrays, that simplifies the problem: