You are constructing a 3-dimensional array, and you are running out of memory. Assuming $data[ 0..X ][ 0..Y ][ 0..Z ];
What we need from you is:
the maximum size of those three dimensions X, Y, Z?
Are the dimensions contiguous or sparse?
If sparse, the approximate density?
If one or more of X,Y & Z can run say 3000 .. 4000; or if instead of using every number between 0 ..m; you only use every 10th or 100th; then you can save substantial space by using a hash instead of an array for that dimension of the structure.
Do you need to build the entire dataset before you can calculate your statistics>
Could you build (say) all of $data[1][Y][Z] for X=1; calculate the stats; and then discard that before building all $data[2][Y][Z] for X=2?
What are you storing in each element of that 3d array?
Is it just a number? If so, how big will that number get?
If, for example, each element of the array held an integer < 255, the you can easily substitute a string for the 3 level arrays and save huge amounts of memory.
Eg. This constructs a 100x100x100 3d array of small integers which requires 33MB of memory.