为什么我的代码作为PHP函数调用时不能输出?


Why won't my code output when called as a PHP function?

在我的文件中,我编写了以下代码:

if ( is_array( $form_data['list'][95] ) ) {
    $i = 1;
    foreach ( $form_data['list'][95] as $row ) {
          /* Uses the column names as array keys */
          $name[$i] = $row['Name'];
          $phonetic[$i] = $row['Phonetic Spelling'];
          if ($phonetic[$i] == ''){$spelling[$i] = '';} else {$spelling[$i] = '('.$phonetic[$i].')';}
          $order[$i] = $row['Order'];
          $full_row[$i] = $order[$i].' - '.$name[$i].' '.$spelling[$i];
          $i++;
    }
rsort($full_row);
    foreach ($full_row as $key => $val) {
    echo "$val<br />";
    }
}

这很好。它输出我所期望的列表。但是,如果我尝试将其作为函数输出,什么也不会发生。

function OrderFormatIntros(){
if ( is_array( $form_data['list'][95] ) ) {
    $i = 1;
    foreach ( $form_data['list'][95] as $row ) {
          /* Uses the column names as array keys */
          $name[$i] = $row['Name'];
          $phonetic[$i] = $row['Phonetic Spelling'];
          if ($phonetic[$i] == ''){$spelling[$i] = '';} else {$spelling[$i] = '('.$phonetic[$i].')';}
          $order[$i] = $row['Order'];
          $full_row[$i] = $order[$i].' - '.$name[$i].' '.$spelling[$i];
          $i++;
    }
rsort($full_row);
    foreach ($full_row as $key => $val) {
    echo "$val<br />";
    }
  }
}
OrderFormatIntros();

我还需要提供更多的解释吗?或者是否有一个明确的原因,为什么代码不会输出作为一个函数调用?

OrderFormatIntros函数内部的代码不知道$form_data变量的内容;您必须将其传递给函数,例如:

<?php
function OrderFormatIntros($form_data){
    if ( is_array( $form_data['list'][95] ) ) {
    $i = 1;
    foreach ( $form_data['list'][95] as $row ) {
    /* Uses the column names as array keys */
        $name[$i] = $row['Name'];
        $phonetic[$i] = $row['Phonetic Spelling'];
        if ($phonetic[$i] == ''){$spelling[$i] = '';} else {$spelling[$i] = '('.$phonetic[$i].')';}
            $order[$i] = $row['Order'];
            $full_row[$i] = $order[$i].' - '.$name[$i].' '.$spelling[$i];
            $i++;
        }
        rsort($full_row);
        foreach ($full_row as $key => $val) {
            echo "$val<br />";
        }
    }
}
OrderFormatIntros($form_data);