I've created a function that returns a nested array based in the values and keys of another two arrays and assigns a third value to the deepest key (hope it makes any sense with the code):
function myfunc_build_array($mydata,$keys,$value)
{
$newarr=array();
foreach ($mydata as $data)
{
$evalvar='$newarr';
foreach ($keys as $key)
{
$evalvar.="['".$data[$key]."']";
}
$evalvar.='=$value;';
eval($evalvar);
}
return $newarr;
}
So, i.e. if we have:
$mydata=array(
0=>array('section'=>'NS1','subsection'=>'NS1A','employee'=>'2812','name'=>'Bob'),
1=>array('section'=>'NS1','subsection'=>'NS1A','employee'=>'2811','name'=>'Bib'),
2=>array('section'=>'NS1','subsection'=>'NS1B','employee'=>'2718','name'=>'Bub'),
);
$keys= array('section','subsection','employee');
The result for myfunc_build_array($mydata,$keys,"active"); is:
array(1) {
["NS1"]=>
array(2) {
["NS1A"]=>
array(2) {
[2812]=>
string(6) "active"
[2811]=>
string(6) "active"
}
["NS1B"]=>
array(1) {
[2718]=>
string(6) "active"
}
}
}
It works fine but as I usually avoid using eval(), I was wondering if there is a better way to do it, more elegant or faster.