PHP未按预期添加到数组

PHP未按预期添加到数组,php,html,forms,Php,Html,Forms,所以,这里是我试图做的一个概述,我正在记录参加活动的学生名单。该列表将与事件的一些其他信息一起存储在一个变量中,这些信息将作为电子邮件发送 我正在尝试这样做,用户只需输入学生姓名[名字][姓氏],每行一个。然后,程序将整个textarea列表作为一个字符串,并将其拆分为新行字符。从这个新创建的列表中,它将按空格字符拆分每个项目,并将列表重新排列为[lastname][comma][firstname],然后为方便起见将其按字母升序排序 我的HTML代码中有一个表单: 提交的信息将转到myscr

所以,这里是我试图做的一个概述,我正在记录参加活动的学生名单。该列表将与事件的一些其他信息一起存储在一个变量中,这些信息将作为电子邮件发送

我正在尝试这样做,用户只需输入学生姓名[名字][姓氏],每行一个。然后,程序将整个textarea列表作为一个字符串,并将其拆分为新行字符。从这个新创建的列表中,它将按空格字符拆分每个项目,并将列表重新排列为[lastname][comma][firstname],然后为方便起见将其按字母升序排序

我的HTML代码中有一个表单:

提交的信息将转到myscript submitted.php并使用POST方法

在表单中,我有一个文本区域:

以下是我的PHP代码:

<?php
    /* get some other variables first */
    $msg = ""; // holds the entire email message body

    /* get the values from the textarea */
    $list = $_POST["stuList"]; // use the 'name' attribute on the textarea

    // split the student list
        $list = explode("\n", $list);
        $newList = array();

        for($i = 0; $i < count($list); $i++) {
            $arr = explode(" ", $list[$i]);

            $fName = $arr[0];
            $lName = $arr[1];

            $newList[] = $lName . ", " . $fName;
        }


        sort($newList);

        for($i = 0; $i < count($newList); $i++) {
            $msg .= ($newList[$i] . "\n");
        }

        mail($toAddr, $subject, $msg, $fromAddr);
?>
列表按姓氏正确排序,但显示如下:

Jones, Andy
Smith
, John
Sue
, Sally

如果需要任何帮助,请告诉我是否需要澄清。

我无法复制OP报告的输出,但希望帮助简化代码,同时仍能获得所需的结果

我使用一个关联数组来简化代码,并消除使用lastName和firstName的必要性。当然,您可以更改代码以仍使用该格式

$list = $_POST["stuList"];
$list = explode("\n", $list);
$newList = array();

foreach ($list as $item) {
    $nameParts = explode(" ", $item);
    $newList[$nameParts[1]] = $item;
}

ksort($newList);

$msg = implode(",\n", $newList)

顺便说一下,您可以使用内爆$message,而不是通过$newList循环创建$message,\n不,我在Mac上,但我可以尝试内爆,看看它是如何工作的。更新:内爆很方便,谢谢,但它仍然在做同样的事情。尝试回显字符串以确定问题是在字符串生成中还是在电子邮件中!谢谢我能够通过将其更改为HTML电子邮件而不仅仅是使用纯文本来解决这个问题。
$list = $_POST["stuList"];
$list = explode("\n", $list);
$newList = array();

foreach ($list as $item) {
    $nameParts = explode(" ", $item);
    $newList[$nameParts[1]] = $item;
}

ksort($newList);

$msg = implode(",\n", $newList)