views:

82

answers:

1

I have some logic that is being used to sort data but depending on the user input the data is grouped differently. Right now I have five different functions that contain the same logic but different groupings. Is there a way to combine these functions and dynamically set a value that will group properly. Within the function these assignments are happening

For example, sometimes I store the calculations simply by:

$calcs[$meter['UnitType']['name']] = ...

but other times need a more specific grouping:

$calcs[$meter['Resource']['name']][$meter['UnitType']['name']][date('Y-m',$start)] =...

As you can see sometimes it is stored in a multidiminesional array and other times not. I have been trying to use eval() but without success (not sure that is the correct approach). Storing the data in a temporary variable does not really save much because there are many nested loops and if statements so the array would have to be repeated in multiple places.

EDIT

I hope the following example explains my problem better. It is obviously a dumbed down version:

if(){
     $calcs[$meter['UnitType']['name']] = $data;
} else {
    while () {
       $calcs[$meter['UnitType']['name']] = $data;
    }
} 

Now the same logic can be used but for storing it in different keys:

if(){
     $calcs[$meter['Resource']['name']][$meter['UnitType']['name']][date('Y-m',$start)] = $data;
} else {
    while () {
       $calcs[$meter['Resource']['name']][$meter['UnitType']['name']][date('Y-m',$start)] = $data;
    }
} 

Is there a way to abstract out the keys in the $calc[] array so that I can have one function instead of having multiple functions with different array keys?

A: 

Would it not be easier to do the following

$calcs = array(
    $meter['Resource']['name'] => array(
        $meter['UnitType']['name'] => 'Some Value',
        $meter['UnitType']['name2'] => 'Some Value Again'
    ),
);

or you can use Objects

$calcs = new stdClass();
$calcs->{$meter['UnitType']['name']} = 'Some Value';

but I would advice you build your structure in arrays and then do!

$calcs = (object)$calcs_array;

or you can loop your first array into a new array!

$new = array();
$d = date('Y-m',$start);
foreach($meter as $key => $value)
{
    $new[$key]['name'][$d] = array();
}

Give it ago and see how the array structure comes out.

RobertPitt
I'm not sure that the question was clear. I have made some edits to try to help explain.
Kramer