我正在使用 PHP 从数据库创建 XML 文档以导入 Adobe InDesign。我希望能够在每个条目后添加逗号,但不能在最后一个条目上添加逗号。我尝试过使用
implode()
但我没有运气。任何帮助将不胜感激。这是没有尝试添加逗号的代码。我可以在结束后添加一个逗号,但这仍然会给我最后一个条目一个逗号。
function getAssocXML ($company) {
$retVal = "";
// Connect to the database by creating a new mysqli object
require_once "DBconnect.php";
$staffResult = $mysql->query("
SELECT company,
fName,
lName,
title,
contact1,
contact2
FROM staff
WHERE company = '$company'
AND title
LIKE '%Associate%'
AND archive = 0
");
if ($staffResult->num_rows >= 1 && $staffResult->num_rows < 4) {
$retVal = $retVal;
for ($i = 0; $i < $staffResult->num_rows; $i++) {
// Move to row number $i in the result set.
$staffResult->data_seek($i);
// Get all the columns for the current row as an associative array -- we named it $aRow
$staffRow = $staffResult->fetch_assoc();
// Write a table row to the output containing information from the current database row.
$retVal = $retVal . "<staff>";
$retVal = $retVal . "<name>" . $staffRow['fName'] . " " . $staffRow['lName'] . "</name>";
$retVal = $retVal . "<contact>" . staffContact($staffRow['contact1'], $staffRow['contact2']) . "</contact>";
$retVal = $retVal . "</staff>";
}
$retVal = $retVal . " — Associate
";
$staffResult->free();
}
if ($staffResult->num_rows > 4) {
$retVal = $retVal;
$retVal = $retVal . "<staffHeader>Associates: </staffHeader>";
for ($i = 0; $i < $staffResult->num_rows; $i++) {
// Move to row number $i in the result set.
$staffResult->data_seek($i);
// Get all the columns for the current row as an associative array -- we named it $aRow
$staffRow = $staffResult->fetch_assoc();
// Write a table row to the output containing information from the current database row.
$retVal = $retVal . "<staff>";
$retVal = $retVal . "<name>" . $staffRow['fName'] . " " . $staffRow['lName'] . "</name>";
$retVal = $retVal . "<contact>" . staffContact($staffRow['contact1'], $staffRow['contact2']) . "</contact>";
$retVal = $retVal . "</staff>";
}
$retVal = $retVal . "
";
$staffResult->free();
}
return $retVal;
}
print getAssocXML(addslashes($aRow['company']));
您可以借助此查询来完成
echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));
或
$last = array_slice($array, -1);
$first = implode(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last), 'strlen');
echo implode(' and ', $both);
恐怕我不太明白你的意图。我在您的代码中没有看到任何使用任何类型数组的内容,这是
implode()
(又名 join()
) 的先决条件
但是,这里有一个小技巧,当我在循环中构建某些东西时,我已经使用过很多次了:
$result = "";
$comma = "";
foreach (...) {
.. calculate some $value ..
$result = $result . $comma . $value;
$comma = ",";
}
循环中的
first时间,$comma
HTH!