删除php中的外部数组
我有一些处理以数组格式提供的数据的函数。这些函数都执行相同的工作,因此我想将它们合并为一个函数。
问题是,它们每个都接收具有不同深度的数组:使用一维、二维和三维数组,并且在未来的某些实现中,甚至可以使用四维数组。
无论如何,重要且必要的数据始终位于最里面的两个数组中,因此我需要删除外部数组,直到只剩下最里面的两个级别。 我的疑问不仅仅是如何做到这一点,而是如何优雅而高效地做到这一点,因为我发现我目前的方法相当笨拙。
当前方法:
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;
}
}
}
一些使用示例:
$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')
)
)
);
当通过 func_get_args() 恢复数据时,所有内容都放在一个额外的数组中。
结果一定是这样的:
array(
array('one', 'two', 'three', 'four', 'five'),
array('six', 'seven', 'eight', 'nine', 'ten')
);
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')
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只有一种方法可以实现这一目标,那就是递归和一点数组函数魔法。这可能不是您确切的解决方案,但应该可以帮助您入门,如果您需要更多帮助,请联系我:
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: