通过索引偶数或奇数拆分数组两个数组 [英] Split array into two arrays by index even or odd
本文介绍了通过索引偶数或奇数拆分数组两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的数组:
$array = array(a, b, c, d, e, f, g);
我想它取决于两个数组拆分如果指数是奇数还是偶数,如:
I want to split it in two arrays depending if the index is even or odd, like this:
$odd = array(a, c, e, g);
$even = array(b, d, f);
在此先感谢!
推荐答案
一个解决方案,使用匿名函数和 array_walk
:
One solution, using anonymous functions and array_walk
:
$odd = array();
$even = array();
$both = array(&$even, &$odd);
array_walk($array, function($v, $k) use ($both) { $both[$k % 2][] = $v; });
这分离在短短的一通阵列上的项目,但它的cleverish边位。这不是真的比任何经典之作,更详细
This separates the items in just one pass over the array, but it's a bit on the "cleverish" side. It's not really any better than the classic, more verbose
$odd = array();
$even = array();
foreach ($array as $k => $v) {
if ($k % 2 == 0) {
$even[] = $v;
}
else {
$odd[] = $v;
}
}
这篇关于通过索引偶数或奇数拆分数组两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文