【问题标题】:how to create a list of variables in a for loop with php如何使用php在for循环中创建变量列表
【发布时间】:2020-12-07 20:27:10
【问题描述】:

txt 文件(translations.txt)中,我有一些绑定到变量的单词行。 txt 文件如下所示:

All Articles
Main Articles
Previous Page
Next Page
// and so on...

要读取所有这些行的内容,我将它们放在一个数组中:

$translationfile = 'data/translations.txt'; 
$lines_translationfile = file($translationfile, FILE_IGNORE_NEW_LINES); // all lines of the txt file into an array
// bind content to variables
$translation0 = $lines_translationfile[0] // All Articles
$translation1 = $lines_translationfile[1] // Main Articles
$translation2 = $lines_translationfile[2] // Previous Page
$translation3 = $lines_translationfile[3] // Next Page
// and so on till 40

我尝试使用 for 循环生成这些变量:

for ($x = 0; $x <= 40; $x++) {
    $translation.$x = $lines_translationfile[$x]; // Does not work...
}

轻松生成所有这些变量直到 40 的正确方法是什么?

【问题讨论】:

  • 为什么需要这些变量?只需使用数组引用。
  • 这些变量的值可能会改变。我让用户进行翻译,他/她的翻译短语将存储在translations.txt 文件中。然后我只需要更改 php 文件的内容,例如带有$translation1的“主要文章”一词
  • 这并不能解释为什么你需要这些变量。在您使用$translation1 的地方,您可以轻松地使用$lines_translationfile[1],尽管我可能会为数组使用一个不那么繁琐的名称。

标签: php for-loop variables


【解决方案1】:

我建议使用数组,但如果您想使用多个变量,请使用以下代码。

for ($x=1; $x < 40; $x++) { 
    ${"translation".$x}=$lines_translationfile[$x];    
}

【讨论】:

    猜你喜欢
    • 2014-05-20
    • 2019-01-04
    • 2021-10-09
    • 2014-11-24
    • 2023-04-01
    • 1970-01-01
    • 2015-12-26
    • 2011-12-08
    • 1970-01-01
    相关资源
    最近更新 更多