php - 使服务器可以理解 php 的循环,而不仅仅是回显代码
问题描述
我必须添加很长的代码
$somephpcode->Cell($string1);
$somephpcode->Cell('Figure 1');
$somephpcode->Cell($string2);
$somephpcode->Cell('Figure 2');
$somephpcode->Cell($string3);
$somephpcode->Cell('Figure 3');
...
我想用循环让它更快。我可以这样:
for ($x = 1; $x <= 25; $x++) {
$somestring = "\$somephpcode->Cell(\$string$x);\$somephpcode->Cell('Figure $x');";
echo $somestring;
}
它会回显正确的代码。但是我的初学者问题是如何使服务器可以理解,而不仅仅是返回(显示)代码?我应该用什么代替回声?可能吗?
解决方案
无需任何重大更改,您只需创建一个包含要引用的变量名称的字符串,然后使用 PHP 的“变量变量”功能来取消引用它:
for ($x = 1; $x <= 25; $x++) {
$varName = 'string' . $x;
// So now $varName contains a string like "string1", and we use two dollar signs here:
$somephpcode->Cell($$varName);
$somephpcode->Cell('Figure ' . $x);
}
但是,任何时候你有变量命名为 var1、var2、var3,你真的应该考虑使用数组来代替。例如:
$strings = ['first string', 'second string', 'third string', ... ];
然后您可以通过从零开始的数字索引来引用第一个字符串,例如$strings[0]
. 这使您的代码更清晰:
for ($x = 1; $x <= 25; $x++) {
$somephpcode->Cell($strings[$x - 1]);
$somephpcode->Cell('Figure ' . $x);
}
推荐阅读
- scala - 在 spark 3.0 中设置 hadoop 配置 - RuntimeException
- java - 壁画计算器。(两种解决方案 - 给出两种不同的结果)
- python - 重新采样熊猫系列(但不是时间系列)
- reactjs - 反应,标记 maxTags 不更新
- c++ - 抽象类型可以用作纯虚函数的返回类型吗?
- kubernetes - 在线精品扩展
- angular - 花费大量时间来更新我的 firebase 项目的字段
- sql - 消息 3623,发生了无效的浮点运算
- c - 传递 char 和整数说明符时,scanf 会做什么?
- azure - Azure 流量管理器终结点更新失败,并显示“resourceTargetId 属性无效或缺失”