我正在使用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']));
答案 0 :(得分:1)
您可以借助此查询
执行此操作echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));
OR
$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);
答案 1 :(得分:0)
我担心我不明白你的意图。我的代码中没有看到任何使用任何类型数组的内容,这是implode()
(a.k.a。join()
)
然而,这是我在循环中构建的时候多次使用的一个小技巧:
$result = "";
$comma = "";
foreach (...) {
.. calculate some $value ..
$result = $result . $comma . $value;
$comma = ",";
}
循环中的第一次时间,$comma
不是逗号!这是一个空字符串。在循环的第一次迭代结束时,它变为逗号,用于 next 时间。这是一种简单但有效的方法,可以就地建立一个任意长度的“逗号分隔字符串”。
HTH!