duanlei4759 2018-12-23 21:12
浏览 170
已采纳

PHP我们将一个字符串变量作为函数的参数

I am trying to set a variable as a string and then use that variable in a while loop function.

<?php
$assoc = <<<'EOF'
$users[]=array('name'=> $row['name'], 'foreman_position'=> $row['foreman_position'], 'status'=> $row['status'], 'emp_num'=>$row['employee_num'],'sen_num'=> $row['seniority_num']);
EOF; 


  while($row = mysqli_fetch_assoc($result)) {
      echo $assoc;

   }

When evaluated I would like it to look like this:

while($row = mysqli_fetch_assoc($result)) {   
     $users[]=array('name'=> $row['name'], 'foreman_position'=> 
     $row['foreman_position'], 'status'=> $row['status'], 'emp_num'=>   
     $row['employee_num'],'sen_num'=> $row['seniority_num']);
   }

If I put the syntax in by hand it works fine but the variable is expressing as the string. Any help is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • donglang2010 2018-12-23 21:31
    关注

    That is just not how this works. If you want to make a piece of code reusable or just move it elsewhere, you use functions:

    function extractResult(array $row, array &$output) {
        $output[] = [... => $row[...], ...];
    }
    
    $users = [];
    
    while ($row = mysqli_fetch_assoc($result)) {
        extractResults($row, $users);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?