对于循环如何分组括号?

时间:2016-03-11 02:07:47

标签: php json for-loop grouping brackets

我有一个问题,在for循环中将括号分组在一起。我使用for循环将锦标赛结果存储在数组中,但是希望按照轮次对结果进行分组。我想分组。看看下面的代码,你可以比较我想改变代码以匹配所需输出的方式:

$tournament_size = 16;

$upper_bracket_total_matches = $tournament_size - 1;
$lower_bracket_total_matches = $tournament_size - 2;

for($i = 1; $i <= $upper_bracket_total_matches; $i++)
{
    $upper_brackets[]= "[0,0]";
}

$upper_bracket_results = implode(",", $upper_brackets)

/* Upper Bracket Output 
[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],
[0,0],[0,0],[0,0],[0,0],
[0,0],[0,0],
[0,0]
*/

/* Desired Upper Bracket Output 
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0]],
[[0,0]]
*/

for($i = 1; $i <= $lower_bracket_total_matches; $i++)
{
    $lower_brackets[]= "[0,0]";
}

$lower_bracket_results = implode(",", $lower_brackets);

/* Lower Bracket Output
[0,0],[0,0],[0,0],[0,0],
[0,0],[0,0],[0,0],[0,0],
[0,0],[0,0],
[0,0],[0,0],
[0,0],
[0,0]
*/

/* Desired Lower bracket Output
[[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0]],
[[0,0],[0,0]],
[[0,0]],
[[0,0]]
*/

希望这很清楚 谢谢你的帮助

卡里姆。

1 个答案:

答案 0 :(得分:0)

试试这个:它根据大小生成东西:

<?php

$tournament_size = 8;
$rounds = log($tournament_size) / log(2);

$upper_bracket_results = array();
$lower_bracket_results = array();

$curr = $tournament_size;

for ($i = 0; $i <= $rounds; $i++) {
    $inner = array();

    for ($i2 = 0; $i2 < $curr; $i2++)
        $inner[] = array(0, 0);

    $curr /= 2;
    $upper_bracket_results[] = $inner;
}

$curr = $tournament_size / 2;

for ($i = 0; $i < $rounds; $i++) {
    $inner = array();

    for ($i2 = 0; $i2 < $curr; $i2++)
        $inner[] = array(0, 0);

     $lower_bracket_results[] = $inner;
     $lower_bracket_results[] = $inner;

    $curr /= 2;
}

echo "Upper:\n\n";
echo json_encode($upper_bracket_results);
echo "\n\nLower:\n\n";
echo json_encode($lower_bracket_results);

Output

Upper:

[[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],[[0,0],[0,0],[0,0],[0,0]],[[0,0],[0,0]],[[0,0]]]

Lower:

[[[0,0],[0,0],[0,0],[0,0]],[[0,0],[0,0],[0,0],[0,0]],[[0,0],[0,0]],[[0,0],[0,0]],[[0,0]],[[0,0]]]