0

我无法理解代码的行为:

输入 :

<?php
    function polldaddy_choices($choices) {
      foreach ($choices as $choice) {
        $answer = "<pd:answer>
                   <pd:text>" . $choice . "</pd:text>
                   </pd:answer>";
        echo $answer; 
     }
  }
  $total_choices = array('yes' , 'no' , 'do not know');
  $ans = polldaddy_choices($total_choices); 
  $xml = "world" . $ans . "hello" ;
  echo $xml;
?>

输出 :

  <pd:answer>
      <pd:text></pd:text>
      </pd:answer><pd:answer>
      <pd:text></pd:text>
      </pd:answer><pd:answer>
      <pd:text></pd:text>
      </pd:answer>worldhello

为什么字符串出现在输出的末尾?

这是键盘上的链接:http: //codepad.org/2dbiCalb

4

3 回答 3

1

您的功能没有重新调整任何内容。您直接在该函数中回显。

所以首先你调用polldaddy_choices,它与 html 相呼应。然后,你回声:

$xml = "world" . "" . "hello" ;
于 2013-03-17T19:55:49.787 回答
1

Because you are echoing the output in your polldaddy_choices function. So the following:

$ans = polldaddy_choices($total_choices); Is actually printing the XML, and:

$xml = "world" . $ans . "hello"; will simply be printing worldhello, as $ans === null

I think you probably want to be doing something more like:

function polldaddy_choices($choices) {
    $answers = array();
    foreach ($choices as $choice) {
        $answer = "<pd:answer>
                   <pd:text>" . $choice . "</pd:text>
                   </pd:answer>";
        $answers[] = $answer;
    }

 return implode("\n", $answers);
}
于 2013-03-17T19:59:27.450 回答
1

您的函数立即回显了 xml 代码。在下面的代码中,您将看到我创建了一个变量 ($answer = "";),然后使用 ".=" 将 xml 附加到变量的末尾。在函数结束时,我返回 $answer 的值。

当您调用函数然后 ($ans = polldaddy_choices($total_choices);) 时,它会将函数的返回值放入您的 $ans 变量中。

<?php
function polldaddy_choices($choices) {
  $answer = "";
  foreach ($choices as $choice) {
    $answer.= "<pd:answer>
               <pd:text>" . $choice . "</pd:text>
               </pd:answer>";
 }
 return $answer;
}
$total_choices = array('yes' , 'no' , 'do not know');
$ans = polldaddy_choices($total_choices); 
$xml = "world" . $ans . "hello" ;
echo $xml;
?>
于 2013-03-17T20:01:25.793 回答