如何在PHP中创建复杂的数组结构

时间:2017-12-01 14:44:07

标签: php arrays

我必须在数组中创建这种结构;

我们有三(3)个变量来创建这个结构:

$numberOfParticipants = 38; // 38 is example
$numberOfParticipantsPerHeat = 8 // 8 is example
$numberOfHeats = 5; // 5 is example

根据这些变量,我有这张表:

The table that I have

问题是,我不能放置' - '或者在31 OR 38之后为null。任务是我必须使数组的数组"几乎相等"喜欢照片,必须依赖上面的变量。顺便说一句,在我创建正确的列表后,我将数组切成5或6或我需要的任何部分这不是问题,问题是我必须首先解析这个列表。这是我到目前为止所尝试的:

    $calc1 = (int)round($numberOfParticipants * $numberOfParticipantsPerHeat, -1); //First round the numberOfParticipants to closest integer by 10


    $readyArr = [];


    for ($i = 1; $i <= $calc1; $i++) {

        if ($i <= $numberOfParticipants) {

            $readyArr[$i] = $i;

        } else {

            $readyArr[$i] = null;
        }

    }

此代码段的问题在于它将null放在列表末尾而不是31之后,或者基于var。 这是我的结果:

array:40 [▼
  1 => 1
  2 => 2
  3 => 3
  4 => 4
  5 => 5
  6 => 6
  7 => 7
  8 => 8
  9 => 9
  10 => 10
  11 => 11
  12 => 12
  13 => 13
  14 => 14
  15 => 15
  16 => 16
  17 => 17
  18 => 18
  19 => 19
  20 => 20
  21 => 21
  22 => 22
  23 => 23
  24 => 24
  25 => 25
  26 => 26
  27 => 27
  28 => 28
  29 => 29
  30 => 30
  31 => 31
  32 => 32
  33 => 33
  34 => 34
  35 => 35
  36 => 36
  37 => 37
  38 => 38
  39 => null
  40 => null
]

我想要的分区之后的数组应该是:

 array(
            0 => array(0 => 1,  1 => 2,  2 => 3,  3 => 4,  4 => 5,  5 => 6,  6 => 7,  7 => 8,),
            1 => array(0 => 9,  1 => 10, 2 => 11, 3 => 12, 4 => 13, 5 => 14, 6 => 15, 7 => 16,),
            2 => array(0 => 17, 1 => 18, 2 => 19, 3 => 20, 4 => 21, 5 => 22, 6 => 23, 7 => 24,),
            3 => array(0 => 25, 1 => 26, 2 => 27, 3 => 28, 4 => 29, 5 => 30, 6 => 31, 7 => null,),
            4 => array(0 => 32, 1 => 33, 2 => 34, 3 => 35, 4 => 36, 5 => 37, 6 => 38, 7 => null,),
        );

每一个帮助,每一条线索都将受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

关于目标结构,您需要了解两件事:

第一个玩家中有多少玩家(总是最大的,只有一个玩家)。

$playersPerHeat = ceil($numberOfParticipants / $numberOfHeats);
// note this replaces your hard-coded $numberOfParticipantsPerHeat

你还需要知道实际上有多少热量,即实际充满的热量。

$fullHeats = $numberOfParticipants % $numberOfHeats ?: $numberOfHeats;
// The ?: bit means that if we get zero (ie. all equal heats), then we
// count all the heats instead, since they're all full.

现在很容易!

$players = range(1,$numberOfParticipants);
$heats = array_merge(
    array_chunk(
        array_slice($players, 0, $fullHeats * $playersPerHeat),
        $playersPerHeat
    ),
    array_chunk(
        array_slice($players, $fullHeats * $playersPerHeat),
        $playersPerHeat - 1
    )
);

就是这样! Demo