PHP - 字符串连接以产生模式


PHP - string concatenation to produce a pattern

我是PHP的新手。我想根据 for 循环条件值生成变量名称。 这是我的代码。

  <?php
    for ( $i = 1; $i < $totalcolumns; $i++ ) 
{
  $pattern1 .= ''$'.'a'.$i'';
}
$pattern = str_repeat ('%d', $totalcolumns);

根据上面的代码,我已经定义了$pattern,以根据总列的值生成%d。$pattern部分在下面的循环中完全没问题。

while (fscanf ($file,''''.$pattern.'''',''''.$pattern1.''''))

因此,例如,如果我的总列值为 3,则上面的 while 循环应该扩展如下。

while (fscanf ($file,'%d%d%d',$a1,$a2,$a3))

模式正在正确扩展,我使用 echo 语句进行了检查。但是,如果我包含用于生成 pattern1 的代码,我的程序不会产生任何输出。

我正在尝试使用变量模式 1 生成模式 $a 1、$a 2、$a 3。我正在使用PHP的字符串连接,但我无法在屏幕中看到任何输出。有人可以指导我朝着正确的方向前进吗?

可以试试这个:

<?php
// You probably might have code here to populate $totalcolumns .
// For test purpose I assumed a value .
    $totalcolumns = 3;
//  Initialize $pattern1
    $pattern1 = '';
//  Make sure weather you need $i < $totalcolumns or $i <= $totalcolumns
    for ( $i = 1; $i < $totalcolumns; $i++ ) 
    {
    //  Your line was $pattern1 .= ''$'.'a'.$i''; which has systax error due to two single quotes before the semicolon
        $pattern1 .= ''$'.'a'.$i;
    }
    echo $pattern1;

将输出:

'$a1'$a2

以上回答了您的(实际)问题。但似乎您需要的是调用一个具有可变参数数量的函数。如果是这种情况,call_user_func_array可以帮助您:


call_user_func_array变量变量
如何将可变数量的参数传递给 PHP 函数

<?php
// You probably might have code here to populate $totalcolumns .
// For test purpose I assumed a value .
    $totalcolumns = 3;
//  Also assuming some values for $a1, $a2, $a3 etc.
    $a1 = 'abc';
    $a2 = 'pqr';
    $a3 = 'xyz';
//  For test purpose I used a string replace it with the actual file handle
    $file = 'File handle';
//  Initialize $pattern
    $pattern = '';
//  Define an array to hold parameters for call_user_func_array
    $parameterArray = array();
//  Put first parameter of fscanf at index 0 of $parameterArray
    $parameterArray[0] = $file;
//  Initialize second parameter of fscanf at index 1 of $parameterArray
    $parameterArray[1] = $pattern;
    $parameterArrayIndex = 2;
    for ( $i = 0; $i < $totalcolumns; $i++ ) 
    {
        $pattern .= '%d';
        $parameterArray[$parameterArrayIndex] = ${"a".($i+1)};  // Variable variables
        $parameterArrayIndex++;
    }
//  Update second parameter of fscanf at index 1 of $parameterArray
    $parameterArray[1] = $pattern;
    var_dump( $parameterArray );
    while( call_user_func_array( 'fscanf', $parameterArray ) )
    {
        //  Do what ever you need to do here
    }
<?php
$totalcolumns = 3
for ( $i = 1; $i <= $totalcolumns; $i++ ){
    $pattern1 .= '$a' . $i . ', ';
}
//remove the last comma and space.
$pattern1 = rtrim($pattern1, ", ");
echo $pattern1;
//$a1, $a2, $a3

完全基于:"我正在尝试生成模式 $a 1、$a 2、$a 3"

我很确定您也不必在单引号中转义美元($)符号。

"''$"

'

$'

然后,如果我想对输出做点什么

<?php
$filledInString = str_replace('$a1', "REPLACED!", $pattern1);
$filledInString = str_replace('$a3', "AGAIN!", $filledInString);
echo $filledInString;
//REPLACED!, $a2, AGAIN!
?>

或者您可能只是在寻找可变变量,但也许这就是您所追求的。邓诺,希望它有帮助:-)