【问题标题】:how to increment variable name by 1 in php如何在php中将变量名增加1
【发布时间】:2020-12-19 11:42:19
【问题描述】:

我有一个关联数组,我在其中将一个字符串绑定到一个变量。 有没有一种简单的方法可以将变量增加 1?

$lang = array(  
    'All Articles' => $t0,
    'Main Articles' => $t1,
    'Archived Articles' => $t2,
    'Search Articles' => $t3,
    'Search for' => $t4,
    'Page' => $t5,
    'from' => $t6,
    // and so on...
);

所以我正在寻找类似的东西,每个示例创建 vars $t0 直到 $t160

我试过了,但没有用:

$i = 0;
$lang = array(  
    'All Articles' => $t.$i++,
    'Main Articles' => $t.$i++,
    'Archived Articles' => $t.$i++,
    'Search Articles' => $t.$i++,
    'Search for' => $t.$i++,
    'Page' => $t.$i++,
    'from' => $t.$i++,

用于:

管理员通过填写表格将翻译后的字符串存储到.txt 文件中。 txt 文件如下所示:

Alle Produkte
Hauptartikel
Archivierte Artikel
// and so on

然后读取文本文件的内容:

$translationfile = 'data/translations.txt'; 
$lines_translationfile = file($translationfile, FILE_IGNORE_NEW_LINES); // all lines of the translations.txt file into an array
for ($x = 0; $x <= 160; $x++) {
    ${"t".$x} = $lines_translationfile[$x];
}
include 'includes/lang.php'; // the associative array

现在在页面中,我可以使用$lang['All Articles'] 轻松翻译字符串

【问题讨论】:

  • 您可以使用递增的变量名称动态构建此数组,但老实说,您应该重新考虑您的设计。拥有大量数字指定的变量可能是一场噩梦。为什么没有立即将这 160 个变量创建为数组或对象?
  • 上面添加的说明

标签: php arrays increment


【解决方案1】:

只需创建一个密钥数组,然后您可以使用array_combine 将它们直接与文件中的行组合:

$translationfile = 'data/translations.txt'; 
$lines_translationfile = file($translationfile, FILE_IGNORE_NEW_LINES); // all lines of the translations.txt file into an array
$keys = array('All Articles','Main Articles','Archived Articles','Search Articles','Search for','Page','from', ...);
$lang = array_combine($keys, $lines_translationfile);

【讨论】:

    【解决方案2】:

    试试这个:

    $i = 0;
    $lang = array(  
        'All Articles' => ${"t".$i++},
        'Main Articles' => ${"t".$i++},
        'Archived Articles' => ${"t".$i++},
        'Search Articles' => ${"t".$i++},
        'Search for' => ${"t".$i++},
        'Page' => ${"t".$i++},
        'from' => ${"t".$i++});
    

    【讨论】:

    • @john 它有效,但请考虑尼克的回答。它更短、更清洁、更高效。
    猜你喜欢
    • 2013-07-03
    • 2012-05-31
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2013-04-27
    • 1970-01-01
    相关资源
    最近更新 更多