gpt4 book ai didi

php - 通过在奇数/偶数数字键上拆分数组,我做错了什么?

转载 作者:行者123 更新时间:2023-12-02 13:49:42 24 4
gpt4 key购买 nike

我在将数组分成两部分时遇到问题。

Array
(
[0] => livree
[1] => 2011-12-26
[2] => livree
[3] => 2011-12-27
[4] => livree
[5] => 2011-12-28
[6] => livree
[7] => 2011-12-29
[8] => livree
[9] => 2011-12-30
[10] => livree
[11] => 2011-12-31
[12] => livree
[13] => 2012-01-01
[14] => livree
[15] => 2012-01-02
[16] => livree
[17] => 2012-01-03
[18] => en_cours
[19] => 2012-01-04
[20] => en_cours
[21] => 2012-01-05
[22] => en_cours
[23] => 2012-01-06
[24] => en_cours
[25] => 2012-01-07
[26] => en_cours
[27] => 2012-01-08
)

我使用这些函数来检测奇数/偶数键并将其分成两个不同的数组:

function odd($var){return($var & 1);}
function even($var){return(!($var & 1));}


$odd = array_filter($vb, "odd");
$even = array_filter($vb, "even");

我只有这两个数组:

Array
(
[0] => 2011-12-26
[1] => 2011-12-27
[2] => 2011-12-28
[3] => 2011-12-29
[4] => 2011-12-30
[5] => 2011-12-31
[6] => 2012-01-01
[7] => livree
[8] => livree
[9] => en_cours
[10] => en_cours
[11] => en_cours
[12] => en_cours
[13] => en_cours
)



Array
(
[0] => livree
[1] => livree
[2] => livree
[3] => livree
[4] => livree
[5] => livree
[6] => livree
[7] => 2012-01-02
[8] => 2012-01-03
[9] => 2012-01-04
[10] => 2012-01-05
[11] => 2012-01-06
[12] => 2012-01-07
[13] => 2012-01-08
)

我做错了什么???感谢您的帮助!

最佳答案

array_filter 向您传递值,而不是键。我无法理解为什么您会得到这些结果,但无论如何,您根本不需要 array_filter:

更快的方法:

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

更可爱的方法:

foreach (array_chunk($vb, 2) as $chunk) {
$even[] = $chunk[0];
$odd[] = $chunk[1];
}

...出于某种原因,我也认为你真的想要一个关联数组:

foreach (array_chunk($vb, 2) as $chunk) {
$days[$chunk[1]] = $chunk[0];
}

关于php - 通过在奇数/偶数数字键上拆分数组,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8778229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com