【问题标题】:Build 500 arrays contain both static text and variablesBuild 500 数组包含静态文本和变量
【发布时间】:2020-02-26 09:00:45
【问题描述】:

我需要构建大约 500 - 800 个数组(或子数组),其中包含静态文本和变量。 每个数组可以有不同的文本和变量,即使某些文本和变量是重复的很常见。

问题:

有没有一种实用的方法可以重用数组结构并生成 500 - 800 个数组? 我需要构建 2 个单独的数组作为源来注入数据吗? (一个数组保存所有变量,一个数组保存所有文本,并明确指示哪个文本属于哪个计划的数组)?

结果也可以是多维数组。

<?php

$id_swedish = 'SEK';

// Array
$unit_1 = [
    'id' => [
      $id_swedish,
      'static_text_1',
      'static_text_2',
      'static_text_3',
      '...',
      'static_text_100',
    ]
];

// Array
$unit_2 = [
    'id' => [
      $id_swedish,
      'other_text_1',
      'other_text_2',
      'other_text_3',
      '...',
      'other_text_100',
    ]
];

print_r($unit_1);
print_r($unit_2);

想要的结果

Array
(
    [id] => Array
        (
            [0] => SEK
            [1] => static_text_1
            [2] => static_text_2
            [3] => static_text_3
            [4] => ...
            [5] => static_text_100
        )

)
Array
(
    [id] => Array
        (
            [0] => SEK
            [1] => other_text_1
            [2] => other_text_2
            [3] => other_text_3
            [4] => ...
            [5] => other_text_100
        )

...等多达 500 - 800 个数组。

【问题讨论】:

    标签: arrays loops for-loop php-7.3


    【解决方案1】:

    为什么不使用array_merge,将重复的静态文本和变量与新的数组项粘合起来?所以你有一个包含公共数据的数组:

    $base_data = [
       $id_swedish,
       'common_static_text_1',
        ...
    ];
    

    然后在生成这些数组的过程中,您使用 array_merge 将它们与基本/默认数据合并:

    $unit_1_id = [
      'static_text_1',
      'static_text_2',
      'static_text_3',
      '...',
      'static_text_100',
    ];
    
    
    $unit_1 = [
    array_merge($base_data, $unit_1_id)
    ];
    

    【讨论】:

    • 工作正常。只需确保迭代生产 500 个数组即可。
    猜你喜欢
    • 2020-07-13
    • 2021-03-11
    • 2012-09-24
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多