gpt4 book ai didi

php - 使用 PHP 从 3 个数组构建一个数组

转载 作者:可可西里 更新时间:2023-11-01 00:19:45 25 4
gpt4 key购买 nike

我在构建数组时遇到了一些问题。

数组A:

Array
(
[0] => 2015-09-13
[1] => 2015-09-14
[2] => 2015-09-15
[3] => 2015-09-16
[4] => 2015-09-17
[5] => 2015-09-18
[6] => 2015-09-19
)

数组 B:

Array
(
[0] => 1
[1] => 8
)

数组 C:

Array
(
[0] => Leaves-19
[1] => Shifts-18
[2] => Shifts-18
[3] => Shifts-18
[4] => Shifts-18
[5] => Shifts-18
[6] => Leaves-19
[7] => Leaves-19
[8] => Shifts-12
[9] => Shifts-12
[10] => Shifts-12
[11] => Shifts-12
[12] => Shifts-12
[13] => Leaves-19
)

期望的最终输出:

Array
(
[0] => 2015-09-13|1|Leaves-19
[1] => 2015-09-14|1|Shifts-18
[2] => 2015-09-15|1|Shifts-18
[3] => 2015-09-16|1|Shifts-18
[4] => 2015-09-17|1|Shifts-18
[5] => 2015-09-18|1|Shifts-18
[6] => 2015-09-19|1|Leaves-19
[7] => 2015-09-13|8|Leaves-19
[8] => 2015-09-14|8|Shifts-12
[9] => 2015-09-15|8|Shifts-12
[10] => 2015-09-16|8|Shifts-12
[11] => 2015-09-17|8|Shifts-12
[12] => 2015-09-18|8|Shifts-12
[13] => 2015-09-19|8|Leaves-19
)

我迷失在 forforeach 中。

逻辑如下:

  • 第一个参数 是一个日期,它来自 array B。是重复6 个条目后。
  • 第二个参数是用户id。它在 6 个条目后更改并传递给下一个 ID。
  • 第三个参数数组B的一个条目。

其他信息:

  • 数组的长度不同。
  • 数组 A,计数为 6 个条目。
  • Array B,计算一个随机条目。
  • 数组 C,是 数组 A x 2。

我已经尝试为我的 array Barray A 中的 foreach 制作一个 for,但它不起作用。

我不知道我需要从哪里开始。

希望我能得到任何帮助或提示。

非常感谢。

最佳答案

你可以使用modulus operator

$OutputArray = Array();

for($i=0; $i < max(count($a1),count($a2),count($a3)); $i++){
array_push($OutputArray, $a1[ $i % count($a1) ] . "|" .
$a2[ $i % count($a2) ] . "|" . $a3[ $i % count($a3) ]);
}

print_r($OutputArray);

你得到:

Array(    [0] => 2015-09-13|1|Leaves-19    [1] => 2015-09-14|8|Shifts-18    [2] => 2015-09-15|1|Shifts-18    [3] => 2015-09-16|8|Shifts-18    [4] => 2015-09-17|1|Shifts-18    [5] => 2015-09-18|8|Shifts-18    [6] => 2015-09-19|1|Leaves-19    [7] => 2015-09-13|8|Leaves-19    [8] => 2015-09-14|1|Shifts-12    [9] => 2015-09-15|8|Shifts-12    [10] => 2015-09-16|1|Shifts-12    [11] => 2015-09-17|8|Shifts-12    [12] => 2015-09-18|1|Shifts-12    [13] => 2015-09-19|8|Leaves-19)

if you want in order (expected):

$OutputArray = Array();

$max = max(count($a1),count($a2),count($a3));
for($i=0; $i < $max; $i++){
array_push($OutputArray, $a1[$i%count($a1)] . "|" .
$a2[ $i*count($a2) / $max ] . "|" . $a3[$i%count($a3)]);
}

print_r($OutputArray);

你得到:

Array(    [0] => 2015-09-13|1|Leaves-19    [1] => 2015-09-14|1|Shifts-18    [2] => 2015-09-15|1|Shifts-18    [3] => 2015-09-16|1|Shifts-18    [4] => 2015-09-17|1|Shifts-18    [5] => 2015-09-18|1|Shifts-18    [6] => 2015-09-19|1|Leaves-19    [7] => 2015-09-13|8|Leaves-19    [8] => 2015-09-14|8|Shifts-12    [9] => 2015-09-15|8|Shifts-12    [10] => 2015-09-16|8|Shifts-12    [11] => 2015-09-17|8|Shifts-12    [12] => 2015-09-18|8|Shifts-12    [13] => 2015-09-19|8|Leaves-19)

关于php - 使用 PHP 从 3 个数组构建一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32570998/

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