I have some functions that deal with data provided in array format. These functions all do the same job, so I would like to merge them into a single function.
The problem is, each of them receives arrays with different depths: one-, two- and three-dimensional arrays are used and, in some future implementations, even four-dimensional arrays may be used.
In any case, the significant and necessary data are always in the two innermost arrays, so I need to get rid of the outer arrays until I have only the innermost two-levels. My doubt is not simply how to do it, but how to do it elegantly and efficiently, as I find my current method rather clumsy.
Current method:
function add() {
$data = func_get_args();
if(count($data)>0) {
if(is_array($data[0])) {
if(is_array($data[0][0])) {
foreach($data[0] as $row) {
$this->items[] = $row;
}
} else {
$this->items[] = $data[0];
}
} else {
$this->items[] = $data;
}
}
}
Some use examples:
$list->add('one', 'two', 'three', 'four', 'five');
$list->add($data_from_DB_in_array_format);
$list->add(
array(
array('one', 'two', 'three', 'four', 'five'),
array('six', 'seven', 'eight', 'nine', 'ten')
)
);
$list->add(
array(
array(
array('one', 'two', 'three', 'four', 'five'),
array('six', 'seven', 'eight', 'nine', 'ten')
)
)
);
As the data is recovered via func_get_args(), everything is put inside an extra array.
The result must be something like this:
array(
array('one', 'two', 'three', 'four', 'five'),
array('six', 'seven', 'eight', 'nine', 'ten')
);