按索引偶数或奇数将数组拆分为两个数组 [英] Split array into two arrays by index even or odd

查看:40
本文介绍了按索引偶数或奇数将数组拆分为两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组:

$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; });

这只是在数组上的一次传递中将项目分开,但这有点聪明"的一面.真的不比经典好,更啰嗦

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆