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(
开发者_C百科 array('one', 'two', 'three', 'four', 'five'),
array('six', 'seven', 'eight', 'nine', 'ten')
);
There is only one way you can achieve this, and it is with recursiveness and a little array function magic. It is probably not your exact solution but should get you started, if you need more help buzz me:
<?php
$data = array(
'test1' => array(
'test2' => array(
'test3' => array(
'test4' => array(
1,
2,
3
),
'test5' => array(
4,
5,
6
),
'test6' => array(
7,
8,
9
),
)
)
)
);
function returnLast2Levels($item){
if(is_array($item) && is_array(reset($item)) && is_array(reset(reset($item)))){
//This $item has more than 2 levels, delve deeper
return returnLast2Levels(reset($item));
}elseif(is_array($item) && is_array(reset($item)) && !is_array(reset(reset($item)))){
//This $item has 2 levels deep of array
return $item;
}
}
var_dump(returnLast2Levels($data));
精彩评论