php 按索引偶数或奇数将数组拆分为两个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12405264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:29:54  来源:igfitidea点击:

Split array into two arrays by index even or odd

phparrayssplit

提问by Marc Vidal Moreno

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!

提前致谢!

回答by Jon

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

这在数组上只通过一次就将项目分开,但这有点“聪明”的一面。它并不比经典更好,更冗长

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

回答by Gareth

Use array_filter(PHP >= 5.6):

使用array_filter(PHP >= 5.6):

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

回答by Fluffeh

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++;
}

回答by biziclop

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 5.5.0+ 具有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_valuestoo:

对于较旧的 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 ));

回答by splash58

One more functional solution with array_chunk and array_map. The last line removes empty item from the 2nd array, when size of a source array is odd

使用 array_chunk 和 array_map 的另一种功能解决方案。当源数组的大小为奇数时,最后一行从第二个数组中删除空项

list($odd, $even) = array_map(null, ...array_chunk($ar,2));
if(count($ar) % 2) array_pop($even);

回答by Krycke

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

回答by Clyde Lobo

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];
    }
}

回答by Meloman

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 :

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

  1. all items {foreach $data.all as $article}...{/foreach}
  2. odd items only {foreach $data.odd as $article}...{/foreach}
  3. even items only {foreach $data.even as $article}...{/foreach}
  1. 所有项目 {foreach $data.all as $article}...{/foreach}
  2. 仅奇数项 {foreach $data.odd as $article}...{/foreach}
  3. 仅偶数项 {foreach $data.even as $article}...{/foreach}

Hope it helps some people...

希望它可以帮助一些人...

回答by Martin

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

回答by MD Sulaiman

    <?php

$array1 = array(0,1,2,3,4,5,6,7,8,9);
$oddarray = array();
$evenarray = array();

$count = 1;

echo "Original: ";
foreach ($array1 as $value)
 {
    echo "$value";
}

echo "<br> Even: ";

foreach ($array1 as $print) 
{
    if ($count%2==1) 
    {
        $evenarray = $print;
        echo "$print";
    }
    $count++;
}

echo "<br> Odd: ";

foreach ($array1 as $print2) {
    if ($count%2!=1) 
    {
        $oddarray[] = $print2;
        echo "$print2";
    }
    $count++;
}

?>

Output:

Original: 0123456789
Even: 02468
Odd: 13579