向回显或保存的Array结果集添加空格和逗号

时间:2014-02-19 07:20:15

标签: php foreach while-loop

任何人都可以帮助我在下面添加空格和逗号,目前我的结果集将打印出这样的内容:

  

TestNameOneTestSurnameOneTestNameTwoTestSurnameTwoTestNameThreeTestSurnameThreeTestNameFourTestSurnameFourTestNameFiveTestSurnameFive

我理想的结果集是:

  

TestNameOne TestSurnameOne,TestNameTwo TestSurnameTwo,TestNameThree TestSurnameThree,TestNameFour TestSurnameFour,TestNameFive TestSurnameFive

代码:

$ctr = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {

    $RespondentsResultSetArray[$ctr] = array(
        "Firstname" => $row['cnt_firstname'],
        "Lastname" => $row['cnt_lastname']
    );

    $ctr = $ctr + 1;
}

foreach ($RespondentsResultSetArray as $key) {
    echo ($key["Firstname"]);
    echo ($key["Lastname"]);
}

sqlsrv_free_stmt($stmt);

我将把这个代码插入一个word文档模板(一个书签),我已经用一个结果和只有一个名称(例如:Joe)定义了这个过程,但是我需要插入以上所有内容正确附加到单词模板中的书签。

2 个答案:

答案 0 :(得分:2)

    $ctr = 0;
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {

        $RespondentsResultSetArray[$ctr] = array(
            "Firstname" => $row['cnt_firstname'],
            "Lastname" => $row['cnt_lastname']
        );

        $ctr++;
    }

   $My_Complete_String = "";
   foreach ($RespondentsResultSetArray as $key) {

       $My_Complete_String .=$key["Firstname"])." ".$key["Lastname"].",";
    }

    rtrim($My_Complete_String, ",");
    echo $My_Complete_String;

    sqlsrv_free_stmt($stmt);

答案 1 :(得分:1)

使用连接

foreach ($RespondentsResultSetArray as $key) {
    echo $key["Firstname"].' '.$key["Lastname"].', ';
}