代码之家  ›  专栏  ›  技术社区  ›  Toolbox

在多维数组中创建新数组,逐步命名每个循环

  •  -1
  • Toolbox  · 技术社区  · 5 年前

    问题:

    它正在按预期与“第1轮”合作。

    <?php
    
    // Create array skeleton.
    
    $array_skeleton = array_fill(1, 3, "");
    
    print_r($array_skeleton);
    
    // Populate the skeleton with random numbers, values [1 to 6].
    
    foreach($array_skeleton as $key => $value) {
        $populated_array[$key] = random_int(1, 6);
    };
    
    print_r($populated_array);
    
    // Create empty array for purpose to become multidimensional array.
    
    $scorecard = [];
    
    // Check if [round_1] is missing, if so create [round_1] and populate it.
    
    if(!array_key_exists("round_1", $scorecard)) {
        echo "round_1 is missing, creating it";
        $scorecard["round_1"] = $populated_array;
    }
    
    print_r($scorecard);
    

    第一次运行脚本后,结果如预期般正常工作:

    (
        [round_1] => Array
            (
                [1] => 3
                [2] => 4
                [3] => 1
            )
    
    )
    

    第二次运行脚本后的预期结果: 注意!正确的是,每个回合的值都是不同的,因为它们是随机创建的。

    (
        [round_1] => Array
            (
                [1] => 3
                [2] => 4
                [3] => 1
            )
         [round_2] => Array
            (
                [1] => 1
                [2] => 4
                [3] => 2
            )
    
    )
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   dWinder Dharman    5 年前

    我认为您的整个代码可以简化:

    首先定义创建随机数数组的函数:

    function createRandomNumberArray($numOfElem, $maxRange) {
        for ($i = 0; $i < $numOfElem; $i++)
            $res[] = random_int(1, $maxRange);
        return $res;
    }
    

    第二,假设你的钥匙是由圆形内景@“你能做的模式

    $biggest = max(array_map(function ($e) {$p = explode("_", $e); return $p[1];}, array_keys($arr)));
    

    现在做:

    $newKey = "round_" . ($biggest + 1);
    $scorecard[$newKey] = createRandomNumberArray(3,6);
    

    参考文献: array-map , explode , max , random-int