通过索引偶数或奇数将数组分割成两个数组

时间:2021-06-16 12:18:05

I have this array:

我有这个数组:

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

Thanks in advance!

提前谢谢!

8 个解决方案

#1


27  

One solution, using anonymous functions and array_walk:

一个解决方案,使用匿名函数和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

这将在数组上的一次传递中分离项,但这在“cleverish”方面有点困难。它并不比经典的好,更冗长

$odd = array();
$even = array();
foreach ($array as $k => $v) {
    if ($k % 2 == 0) {
        $even[] = $v;
    }
    else {
        $odd[] = $v;
    }
}

#2


6  

Use array_filter:

使用array_filter:

$odd=array_filter($array, function ($input) {return $input & 1;});
$even=array_filter($array, function ($input) {return !($input & 1);});

#3


3  

I am not sure if this is the most elegant way, but it should work a charm:

我不确定这是否是最优雅的方式,但它应该具有魅力:

$odd=array();
$even=array();
$count=1;
foreach($array as $val)
{
    if($count%2==1)
    {
        $odd[]=$val;
    }
    else
    {
        $even[]=$val;
    }
    $count++;
}

#4


2  

As an almost-one-liner, I think this will be my favourite:

作为一个几乎是一行的人,我认为这将是我的最爱:

$even = $odd = array();
foreach( $array as $k => $v )  $k % 2  ?  $odd[] = $v  :  $even[] = $v;

Or for a tiny little more? speed:

还是为了再多一点点?速度:

$even = $odd = array();
foreach( $array as $k => $v )  ( $k & 1 ) === 0  ?  $even[] = $v  :  $odd[] = $v;

A bit more verbose variant:

更详细的变体:

$both = array( array(), array() );
// or, if $array has at least two elements:
$both = array();

foreach( $array as $k => $v )  $both[ $k % 2 ][] = $v;
list( $even, $odd ) = $both;

With array_chunk:

array_chunk:

$even = $odd = array();
foreach( array_chunk( $array, 2 ) as $chunk ){
  list( $even[], $odd[] ) = isset( $chunk[1]) ? $chunk : $chunk + array( null, null );
  // or, to force even and odd arrays to have the same count:
  list( $even[], $odd[] ) = $chunk + array( null, null );
}

If $array is guaranteed to have even number of elements:

如果$array保证有偶数个元素:

$even = $odd = array();
foreach( array_chunk( $array, 2 ) as $chunk )
  list( $even[], $odd[] ) = $chunk;

PHP 5.5.0+ with array_column:

PHP发送+ array_column:

$chunks = array_chunk( $array, 2 );
$even = array_column( $chunks, 0 );
$odd  = array_column( $chunks, 1 );

Something similar for older PHP versions. The keys will be 0,2,4,… and 1,3,5,…. If you don't like this, apply an array_values too:

类似于旧的PHP版本。键将0、2、4,,1,3,5,....如果你不喜欢这个,也可以应用array_values:

$even = array_intersect_key( $array, array_flip( range( 0, count( $array ), 2 )));
$odd  = array_intersect_key( $array, array_flip( range( 1, count( $array ), 2 )));

or

$even = array_intersect_key( $array, array_fill_keys( range( 0, count( $array ), 2 ), null ));
$odd  = array_intersect_key( $array, array_fill_keys( range( 1, count( $array ), 2 ), null ));

#5


1  

Just loop though them and check if the key is even or odd:

只需循环遍历它们,检查键是否为偶数或奇数:

$odd = array();
$even = array();
foreach( $array as $key => $value ) {
    if( 0 === $key%2) { //Even
        $even[] = $value;
    }
    else {
        $odd[] = $value;
    }
}

#6


1  

One

一个

$odd = $even = array();
for ($i = 0, $l = count($array ); $i < $l;) { // Notice how we increment $i each time we use it below, by two in total
    $even[] = $array[$i++];
    if($i < $l)
    {
       $odd[] = $array[$i++];
    }
}

Two

两个

$odd = $even = array();
foreach (array_chunk($array , 2) as $chunk) {
    $even[] = $chunk[0];
    if(!empty( $chunk[1]))
    {
       $odd[] = $chunk[1];
    }
}

#7


1  

Based on @Jon's second variant, I made this following for use with PHP Smarty v3 template engine. This is for displaying news/blog with both one or two columns template model.

基于@Jon的第二个变体,我将其用于PHP Smarty v3模板引擎。这是用来显示新闻/博客的一个或两个列模板模型。

After the MySql query I'll do the following code :

在MySql查询之后,我将执行以下代码:

if(sizeof($results) > 0) {
    $data = array();
    foreach($results as $k => $res) {
        if($k % 2 == 0) {
            $res["class"] = "even";
            $data["all"][] = $data["even"][] = $res;
        }
        else {
            $res["class"] = "odd";
            $data["all"][] = $data["odd"][] = $res;
        }
    }
}

I obtain an array of 3 sub-arrays (including odd/even class) with Smarty syntax of use :

我获得了一个包含3个子数组(包括奇数/偶数类)的数组,具有使用Smarty语法:

  1. all items {foreach $data.all as $article}...{/foreach}
  2. 所有项目{ foreach $数据。所有文章美元} { / foreach }…
  3. odd items only {foreach $data.odd as $article}...{/foreach}
  4. 奇数项仅为每$数据的{。奇怪的文章美元} { / foreach }…
  5. even items only {foreach $data.even as $article}...{/foreach}
  6. 甚至项目只针对每个$数据。尽管美元条} { / foreach }…

Hope it helps some people...

希望它能帮助一些人…

#8


1  

$odd = [];
$even = [];
while (count($arr)) {
    $odd[] = array_shift($arr);
    $even[] = array_shift($arr);
}

#1


27  

One solution, using anonymous functions and array_walk:

一个解决方案,使用匿名函数和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

这将在数组上的一次传递中分离项,但这在“cleverish”方面有点困难。它并不比经典的好,更冗长

$odd = array();
$even = array();
foreach ($array as $k => $v) {
    if ($k % 2 == 0) {
        $even[] = $v;
    }
    else {
        $odd[] = $v;
    }
}

#2


6  

Use array_filter:

使用array_filter:

$odd=array_filter($array, function ($input) {return $input & 1;});
$even=array_filter($array, function ($input) {return !($input & 1);});

#3


3  

I am not sure if this is the most elegant way, but it should work a charm:

我不确定这是否是最优雅的方式,但它应该具有魅力:

$odd=array();
$even=array();
$count=1;
foreach($array as $val)
{
    if($count%2==1)
    {
        $odd[]=$val;
    }
    else
    {
        $even[]=$val;
    }
    $count++;
}

#4


2  

As an almost-one-liner, I think this will be my favourite:

作为一个几乎是一行的人,我认为这将是我的最爱:

$even = $odd = array();
foreach( $array as $k => $v )  $k % 2  ?  $odd[] = $v  :  $even[] = $v;

Or for a tiny little more? speed:

还是为了再多一点点?速度:

$even = $odd = array();
foreach( $array as $k => $v )  ( $k & 1 ) === 0  ?  $even[] = $v  :  $odd[] = $v;

A bit more verbose variant:

更详细的变体:

$both = array( array(), array() );
// or, if $array has at least two elements:
$both = array();

foreach( $array as $k => $v )  $both[ $k % 2 ][] = $v;
list( $even, $odd ) = $both;

With array_chunk:

array_chunk:

$even = $odd = array();
foreach( array_chunk( $array, 2 ) as $chunk ){
  list( $even[], $odd[] ) = isset( $chunk[1]) ? $chunk : $chunk + array( null, null );
  // or, to force even and odd arrays to have the same count:
  list( $even[], $odd[] ) = $chunk + array( null, null );
}

If $array is guaranteed to have even number of elements:

如果$array保证有偶数个元素:

$even = $odd = array();
foreach( array_chunk( $array, 2 ) as $chunk )
  list( $even[], $odd[] ) = $chunk;

PHP 5.5.0+ with array_column:

PHP发送+ array_column:

$chunks = array_chunk( $array, 2 );
$even = array_column( $chunks, 0 );
$odd  = array_column( $chunks, 1 );

Something similar for older PHP versions. The keys will be 0,2,4,… and 1,3,5,…. If you don't like this, apply an array_values too:

类似于旧的PHP版本。键将0、2、4,,1,3,5,....如果你不喜欢这个,也可以应用array_values:

$even = array_intersect_key( $array, array_flip( range( 0, count( $array ), 2 )));
$odd  = array_intersect_key( $array, array_flip( range( 1, count( $array ), 2 )));

or

$even = array_intersect_key( $array, array_fill_keys( range( 0, count( $array ), 2 ), null ));
$odd  = array_intersect_key( $array, array_fill_keys( range( 1, count( $array ), 2 ), null ));

#5


1  

Just loop though them and check if the key is even or odd:

只需循环遍历它们,检查键是否为偶数或奇数:

$odd = array();
$even = array();
foreach( $array as $key => $value ) {
    if( 0 === $key%2) { //Even
        $even[] = $value;
    }
    else {
        $odd[] = $value;
    }
}

#6


1  

One

一个

$odd = $even = array();
for ($i = 0, $l = count($array ); $i < $l;) { // Notice how we increment $i each time we use it below, by two in total
    $even[] = $array[$i++];
    if($i < $l)
    {
       $odd[] = $array[$i++];
    }
}

Two

两个

$odd = $even = array();
foreach (array_chunk($array , 2) as $chunk) {
    $even[] = $chunk[0];
    if(!empty( $chunk[1]))
    {
       $odd[] = $chunk[1];
    }
}

#7


1  

Based on @Jon's second variant, I made this following for use with PHP Smarty v3 template engine. This is for displaying news/blog with both one or two columns template model.

基于@Jon的第二个变体,我将其用于PHP Smarty v3模板引擎。这是用来显示新闻/博客的一个或两个列模板模型。

After the MySql query I'll do the following code :

在MySql查询之后,我将执行以下代码:

if(sizeof($results) > 0) {
    $data = array();
    foreach($results as $k => $res) {
        if($k % 2 == 0) {
            $res["class"] = "even";
            $data["all"][] = $data["even"][] = $res;
        }
        else {
            $res["class"] = "odd";
            $data["all"][] = $data["odd"][] = $res;
        }
    }
}

I obtain an array of 3 sub-arrays (including odd/even class) with Smarty syntax of use :

我获得了一个包含3个子数组(包括奇数/偶数类)的数组,具有使用Smarty语法:

  1. all items {foreach $data.all as $article}...{/foreach}
  2. 所有项目{ foreach $数据。所有文章美元} { / foreach }…
  3. odd items only {foreach $data.odd as $article}...{/foreach}
  4. 奇数项仅为每$数据的{。奇怪的文章美元} { / foreach }…
  5. even items only {foreach $data.even as $article}...{/foreach}
  6. 甚至项目只针对每个$数据。尽管美元条} { / foreach }…

Hope it helps some people...

希望它能帮助一些人…

#8


1  

$odd = [];
$even = [];
while (count($arr)) {
    $odd[] = array_shift($arr);
    $even[] = array_shift($arr);
}