簡體   English   中英

如何在 php 中將變量名稱增加 1

[英]how to increment variable name by 1 in php

我有一個關聯數組,在其中我將一個字符串綁定到一個變量。 有沒有一種簡單的方法可以將變量增加 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']輕松翻譯字符串

嘗試這個:

$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++});

只需創建一個鍵數組,然后您可以使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM